Example usage for javax.security.auth.login LoginContext login

List of usage examples for javax.security.auth.login LoginContext login

Introduction

In this page you can find the example usage for javax.security.auth.login LoginContext login.

Prototype

public void login() throws LoginException 

Source Link

Document

Perform the authentication.

Usage

From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java

/**
 * Perform JAAS login.//from  w  w  w.jav  a  2 s . com
 *
 * @return the logged-in subject or null if login failed.
 */
protected Subject performJAASLogin() {
    CallbackHandler lch = getLoginCallbackHandler();
    try {
        LoginContext lc;
        try {
            lc = new LoginContext(getLoginContextName(), lch);
        } catch (LoginException le) {
            LOG.error("Cannot create LoginContext.", le);
            return null;
        } catch (SecurityException se) {
            LOG.error("Cannot create LoginContext.", se);
            return null;
        }
        lc.login();
        return lc.getSubject();
    } catch (LoginException le) {
        // le.getCause() is always null, so cannot rely on it.
        // see bug #1019
        if (!(le instanceof FailedLoginException)) {
            String message = le.getMessage();
            if (message.indexOf(':') > 0) {
                String exceptionClassName = message.substring(0, message.indexOf(':'));
                try {
                    if (Throwable.class.isAssignableFrom(Class.forName(exceptionClassName))) {
                        LOG.error("A technical exception occurred on login module.", le);
                    }
                } catch (ClassNotFoundException ignored) {
                    // ignored.
                }
            }
        }
        return null;
    }
}

From source file:org.kalypso.test.bsu.wfs.SingleSignonTest.java

public void testSigngleSignon() throws Exception {
    try {//w ww .  ja va 2 s.  com
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAStestLogin.html"));
        LoginContext loginContext = null;
        System.setProperty("java.security.auth.login.config", "D:/eclipse3.1/tmp/jaasConf.txt");
        // Login-Kontext fr die Konfiguration "Demo" erzeugen
        // loginContext = new LoginContext( "Demo" );
        loginContext = new LoginContext("Demo", new CallbackHandler() {

            public void handle(Callback[] callbacks) {
                for (int i = 0; i < callbacks.length; i++) {
                    Callback callback = callbacks[i];
                    if (callback instanceof NameCallback) {
                        final NameCallback nCall = (NameCallback) callback;
                        System.out.println(nCall.getPrompt());
                        nCall.setName("Flowsad");
                    } else if (callback instanceof PasswordCallback) {
                        final PasswordCallback call = (PasswordCallback) callback;
                        System.out.println(call.getPrompt());
                        call.setPassword(new char[] { ' ', ' ', });
                    } else
                        System.out.println("unknown Callback: " + callback.getClass().getName());
                }
            }

        });
        // Durchfhrung des Logins
        loginContext.login();
        System.out.println("authentication succeeded");

        // Die Principals ermitteln...
        Set principals = loginContext.getSubject().getPrincipals();
        // ...und in einer Iteration ausgeben
        Iterator it = principals.iterator();
        Principal p;
        while (it.hasNext()) {
            p = (Principal) it.next();
            System.out.println(p);
        }
        System.out.println("logging out...");
        copy(new File("D:/eclipse3.1/tmp/web_FlowsAdmitLogin.html"));

        loginContext.logout();
    } catch (Exception e) {
        System.out.println("authentication failed");
        throw e;
    }
}

From source file:org.lsc.jndi.JndiServices.java

public static Properties getLdapProperties(LdapConnectionType connection) throws LscConfigurationException {
    Properties props = new Properties();
    props.setProperty(DirContext.INITIAL_CONTEXT_FACTORY,
            (connection.getFactory() != null ? connection.getFactory() : "com.sun.jndi.ldap.LdapCtxFactory"));
    props.put(TLS_CONFIGURATION, connection.isTlsActivated());
    if (connection.getUsername() != null) {
        props.setProperty(DirContext.SECURITY_AUTHENTICATION, connection.getAuthentication().value());
        props.setProperty(DirContext.SECURITY_PRINCIPAL, connection.getUsername());
        if (connection.getAuthentication().equals(LdapAuthenticationType.GSSAPI)) {
            if (System.getProperty("java.security.krb5.conf") != null) {
                throw new RuntimeException("Multiple Kerberos connections not supported (existing value: "
                        + System.getProperty("java.security.krb5.conf")
                        + "). Need to set another LSC instance or unset system property !");
            } else {
                System.setProperty("java.security.krb5.conf",
                        new File(Configuration.getConfigurationDirectory(), "krb5.ini").getAbsolutePath());
            }// ww  w  .j a  v  a  2 s . co  m
            if (System.getProperty("java.security.auth.login.config") != null) {
                throw new RuntimeException("Multiple JAAS not supported (existing value: "
                        + System.getProperty("java.security.auth.login.config")
                        + "). Need to set another LSC instance or unset system property !");
            } else {
                System.setProperty("java.security.auth.login.config",
                        new File(Configuration.getConfigurationDirectory(), "gsseg_jaas.conf")
                                .getAbsolutePath());
            }
            props.setProperty("javax.security.sasl.server.authentication",
                    "" + connection.isSaslMutualAuthentication());
            //            props.put("java.naming.security.sasl.authorizationId", "dn:" + connection.getUsername());
            props.put("javax.security.auth.useSubjectCredsOnly", "true");
            props.put("com.sun.jndi.ldap.trace.ber", System.err); //debug trace
            props.setProperty("javax.security.sasl.qop", connection.getSaslQop().value());
            try {
                LoginContext lc = new LoginContext(JndiServices.class.getName(),
                        new KerberosCallbackHandler(connection.getUsername(), connection.getPassword()));
                lc.login();
            } catch (LoginException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            props.setProperty(DirContext.SECURITY_CREDENTIALS, connection.getPassword());
        }
    } else {
        props.setProperty(DirContext.SECURITY_AUTHENTICATION, "none");
    }
    try {
        LdapUrl connectionUrl = new LdapUrl(connection.getUrl());
        if (connectionUrl.getHost() == null) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug(
                        "Hostname is empty in LDAP URL, will try to lookup through the naming context ...");
            String domainExt = convertToDomainExtension(connectionUrl.getDn());
            if (domainExt != null) {
                String hostname = lookupLdapSrvThroughDNS("_ldap._tcp." + domainExt);
                if (hostname != null) {
                    connectionUrl.setHost(hostname.substring(0, hostname.indexOf(":")));
                    connectionUrl.setPort(Integer.parseInt(hostname.substring(hostname.indexOf(":") + 1)));
                    connection.setUrl(connectionUrl.toString());
                }
            }
        }
    } catch (LdapURLEncodingException e) {
        throw new LscConfigurationException(e);
    }
    props.setProperty(DirContext.PROVIDER_URL, connection.getUrl());
    if (connection.getReferral() != null) {
        props.setProperty(DirContext.REFERRAL, connection.getReferral().value().toLowerCase());
    } else {
        props.setProperty(DirContext.REFERRAL, LdapReferralType.IGNORE.value().toLowerCase());
    }
    if (connection.getDerefAliases() != null) {
        props.setProperty("java.naming.ldap.derefAliases", getDerefJndiValue(connection.getDerefAliases()));
    } else {
        props.setProperty("java.naming.ldap.derefAliases", getDerefJndiValue(LdapDerefAliasesType.NEVER));
    }
    if (connection.getBinaryAttributes() != null) {
        props.setProperty("java.naming.ldap.attributes.binary",
                StringUtils.join(connection.getBinaryAttributes().getString(), " "));
    }
    if (connection.getPageSize() != null) {
        props.setProperty("java.naming.ldap.pageSize", "" + connection.getPageSize());
    }
    if (connection.getSortedBy() != null) {
        props.setProperty("java.naming.ldap.sortedBy", connection.getSortedBy());
    }
    props.setProperty("java.naming.ldap.version",
            (connection.getVersion() == LdapVersionType.VERSION_2 ? "2" : "3"));
    if (connection.isRecursiveDelete() != null) {
        props.setProperty("java.naming.recursivedelete", Boolean.toString(connection.isRecursiveDelete()));
    }

    return props;
}

From source file:org.nuxeo.ecm.platform.oauth2.openid.web.OAuth2CallbackHandlerServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // Getting the "error" URL parameter
    String error = req.getParameter(ERROR_URL_PARAM_NAME);

    // / Checking if there was an error such as the user denied access
    if (error != null && error.length() > 0) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \"" + error + "\".");
        return;/*from ww w.  ja v a 2s. c om*/
    }

    // Getting the "code" URL parameter
    String code = req.getParameter(CODE_URL_PARAM_NAME);

    // Checking conditions on the "code" URL parameter
    if (code == null || code.isEmpty()) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was an error: \"" + error + "\".");
        return;
    }

    String path = req.getRequestURI().split(URL_MAPPING + "/")[1];
    String[] parts = path.split("/");
    String serviceProviderName = parts[0];

    NuxeoOAuth2ServiceProvider provider;
    try {
        provider = getServiceProvider(serviceProviderName);

        if (provider == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "No service provider called: \"" + serviceProviderName + "\".");
            return;
        }

        AuthorizationCodeFlow flow = provider.getAuthorizationCodeFlow(HTTP_TRANSPORT, JSON_FACTORY);

        String redirectUri = req.getRequestURL().toString();

        Principal principal = req.getUserPrincipal();

        HttpResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).executeUnparsed();
        TokenResponse tokenResponse = response.parseAs(TokenResponse.class);

        // Validate the token
        String accessToken = tokenResponse.getAccessToken();

        HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setParser(new JsonObjectParser(JSON_FACTORY));
            }
        });

        GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v1/tokeninfo");
        url.set("access_token", accessToken);

        HttpRequest request = requestFactory.buildGetRequest(url);
        response = request.execute();

        // TODO - get the email
        String email = "nelson.silva@gmail.com";

        UserManager manager = Framework.getLocalService(UserManager.class);

        Map<String, Serializable> query = new HashMap<String, Serializable>();
        query.put(manager.getUserEmailField(), email);

        DocumentModelList users = manager.searchUsers(query, null);

        if (users.isEmpty()) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No user found with email: \"" + email + "\".");
        }

        DocumentModel user = users.get(0);
        String userId = (String) user.getPropertyValue(manager.getUserIdField());

        Framework.loginAs(userId);
        LoginContext loginContext = NuxeoAuthenticationFilter.loginAs(userId);
        loginContext.login();

        resp.sendRedirect(req.getContextPath());
    } catch (Exception e) {
        log.error("Error while processing OAuth2 Callback", e);
    }

}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

protected Principal doAuthenticate(CachableUserIdentificationInfo cachableUserIdent,
        HttpServletRequest httpRequest) {

    LoginContext loginContext;
    try {//  w  w w . j  a  v  a2  s  .c om
        CallbackHandler handler = service.getCallbackHandler(cachableUserIdent.getUserInfo());
        loginContext = new LoginContext(securityDomain, handler);

        if (isLoginSynchronized()) {
            synchronized (NuxeoAuthenticationFilter.class) {
                loginContext.login();
            }
        } else {
            loginContext.login();
        }

        Principal principal = (Principal) loginContext.getSubject().getPrincipals().toArray()[0];
        cachableUserIdent.setPrincipal(principal);
        cachableUserIdent.setAlreadyAuthenticated(true);
        // re-set the userName since for some SSO based on token,
        // the userName is not known before login is completed
        cachableUserIdent.getUserInfo().setUserName(principal.getName());

        logAuthenticationAttempt(cachableUserIdent.getUserInfo(), true);
    } catch (LoginException e) {
        log.info("Login failed for " + cachableUserIdent.getUserInfo().getUserName());
        logAuthenticationAttempt(cachableUserIdent.getUserInfo(), false);
        Throwable cause = e.getCause();
        if (cause instanceof DirectoryException) {
            Throwable rootCause = ExceptionUtils.getRootCause(cause);
            if (rootCause instanceof NamingException
                    && rootCause.getMessage().contains("LDAP response read timed out")
                    || rootCause instanceof SocketException) {
                httpRequest.setAttribute(LOGIN_STATUS_CODE, HttpServletResponse.SC_GATEWAY_TIMEOUT);
            }
            return DIRECTORY_ERROR_PRINCIPAL;
        }
        return null;
    }

    // store login context for the time of the request
    // TODO logincontext is also stored in cachableUserIdent - it is really
    // needed to store it??
    httpRequest.setAttribute(LOGINCONTEXT_KEY, loginContext);

    // store user ident
    cachableUserIdent.setLoginContext(loginContext);
    boolean createSession = needSessionSaving(cachableUserIdent.getUserInfo());
    HttpSession session = httpRequest.getSession(createSession);
    if (session != null) {
        session.setAttribute(USERIDENT_KEY, cachableUserIdent);
    }

    service.onAuthenticatedSessionCreated(httpRequest, session, cachableUserIdent);

    return cachableUserIdent.getPrincipal();
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter.java

/**
 * Does a forced login as the given user. Bypasses all authentication checks.
 *
 * @param username the user name/* ww w.  jav  a  2 s  .  c om*/
 * @return the login context, which MUST be used for logout in a {@code finally} block
 * @throws LoginException
 */
public static LoginContext loginAs(String username) throws LoginException {
    UserIdentificationInfo userIdent = new UserIdentificationInfo(username, "");
    userIdent.setLoginPluginName(TrustingLoginPlugin.NAME);
    PluggableAuthenticationService authService = (PluggableAuthenticationService) Framework.getRuntime()
            .getComponent(PluggableAuthenticationService.NAME);
    CallbackHandler callbackHandler;
    if (authService != null) {
        callbackHandler = authService.getCallbackHandler(userIdent);
    } else {
        callbackHandler = new UserIdentificationInfoCallbackHandler(userIdent);
    }
    LoginContext loginContext = new LoginContext(LOGIN_DOMAIN, callbackHandler);

    if (isLoginSynchronized()) {
        synchronized (NuxeoAuthenticationFilter.class) {
            loginContext.login();
        }
    } else {
        loginContext.login();
    }
    return loginContext;
}

From source file:org.opengroupware.logic.auth.OGoLoginModule.java

/**
 * This is a convenience function which sets up a JAAS login context with the
 * default database configuration,//  w  w w  .j a  va2s.  co  m
 * and then performs a login with the given login/password.
 * 
 * @param _db   - a setup OGoDatabase object
 * @param _user - the login name
 * @param _pwd  - the login password
 * @return null if the login failed, otherwise the LoginContext
 */
public static LoginContext jaasLogin(final EODatabase _db, final String _user, final String _pwd) {
    if (_db == null) {
        log.warn("got no database for JAAS login of user: " + _user);
        return null;
    }

    final Subject subject = new Subject();
    LoginContext jlc = null;
    try {
        jlc = new LoginContext("OGo", /* application     */
                subject, /* subject */
                new NamePasswordCallbackHandler(_user, _pwd), /* CallbackHandler */
                new OGoDefaultLoginConfig(_db) /* configuration */);
    } catch (LoginException e) {
        log.error("could not setup JAAS LoginContext", e);
    }
    if (jlc == null)
        return null;

    /* login */

    try {
        jlc.login();
    } catch (LoginException e) {
        jlc = null;
        return null;
    }

    return jlc;
}

From source file:org.openhab.io.net.http.SecureHttpContext.java

/**
 * <p>Authenticates the given <code>username</code> and <code>password</code>
 * with respect to the given <code>realm</code> against the configured
 * {@link LoginModule} (see login.conf in &lt;openhabhome&gt;/etc to learn
 * more about the configured {@link LoginModule})</p>
 * <p><b>Note:</b>Roles aren't supported yet!</p>
 * //from w w  w  .  j ava2s.co  m
 * @param realm the realm used by the configured {@link LoginModule}. 
 * <i>Note:</i> the given <code>realm</code> must be same name as configured
 * in <code>login.conf</code>
 * @param username
 * @param password
 * 
 * @return a {@link Subject} filled with username, password, realm, etc. or
 * <code>null</code> if the login failed
 * @throws UnsupportedCallbackException if a {@link Callback}-instance other
 * than {@link NameCallback} or {@link ObjectCallback} is going to be handled
 */
private Subject authenticate(final String realm, final String username, final String password) {
    try {
        logger.trace("going to authenticate user '{}', realm '{}'", username, realm);

        Subject subject = new Subject();

        LoginContext lContext = new LoginContext(realm, subject, new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    if (callbacks[i] instanceof NameCallback) {
                        ((NameCallback) callbacks[i]).setName(username);
                    } else if (callbacks[i] instanceof ObjectCallback) {
                        ((ObjectCallback) callbacks[i]).setObject(password);
                    } else {
                        throw new UnsupportedCallbackException(callbacks[i]);
                    }
                }
            }
        });
        lContext.login();

        // TODO: TEE: implement role handling here!

        return subject;
    } catch (LoginException le) {
        logger.warn("authentication of user '" + username + "' failed", le);
        return null;
    }
}

From source file:org.processbase.ui.core.BPMModule.java

public User authUserWithJaas(String username, String password) {
    try {/*from   w  w  w.j a va  2  s. c o  m*/
        LoginContext ctx = new LoginContext("SmartBPM", new ProcessbaseAuthCallbackHandler(username, password));
        ctx.login();
        //ctx.getSubject().getPrincipals();
        return null;
    } catch (Exception e) {
        logger.error("AuthUser", e);
    }
    return null;
}

From source file:org.qualipso.factory.ui.core.login.server.LoginServletImpl.java

/**
 * Try to log in the factory using the given username and password.
 * /*from ww  w . java 2 s .c om*/
 * @see org.qualipso.factory.ui.core.login.client.LoginServlet#login(java.lang.String, java.lang.String)
 * 
 * @param username
 *            the username
 * @param password
 *            the password
 * @return true if the user information allow him to log in, false otherwise
 */
public Boolean login(String username, String password) {
    logger.info("User " + username + " trying to log on the factory...");

    // clean old login session if necessary
    HttpSession session = getThreadLocalRequest().getSession(false);
    if (session != null) {
        session.removeAttribute(USERNAME_SESSION_ATTRIBUTE);
        session.removeAttribute(PASSWORD_SESSION_ATTRIBUTE);
        session.invalidate();
    }

    // get the naming context for lookup factory services
    final Context namingContext;
    try {
        final Properties properties = new Properties();
        properties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
        properties.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
        properties.put("java.naming.provider.url", "localhost:1099");
        namingContext = new InitialContext(properties);
    } catch (NamingException ne) {
        logger.error("Cannot manage to access Factory through naming. Caused by: ", ne);
        return false;
    }

    // check the application context to see if the bootstrap has already been done
    // thanks to Jerome for this piece of code
    String bootstrapped = (String) getThreadLocalRequest().getSession().getServletContext()
            .getAttribute(BOOTSTRAPPED_FLAG);
    if (bootstrapped == null) {
        logger.info("No bootstrap flag found in the application context.");
        logger.info("Bootstrap of the factory is needed, in progress....");
        try {
            BootstrapService bootstrap = (BootstrapService) namingContext
                    .lookup(FactoryNamingConvention.getJNDINameForService(BootstrapService.SERVICE_NAME));
            bootstrap.bootstrap();
            getThreadLocalRequest().getSession().getServletContext().setAttribute(BOOTSTRAPPED_FLAG,
                    BOOTSTRAPPED_FLAG);
            logger.info("Bootstrap of the factory done.");
        } catch (NamingException ne) {
            logger.error("Cannot manage to access Factory bootstrap service. Caused by: ", ne);
            return false;
        } catch (BootstrapServiceException bse) {
            logger.error("Cannot manage to call Factory bootstrap service. Caused by: ", bse);
            return false;
        }
    } else {
        logger.info("Bootstrap flag found in the application context, no need to bootstrap.");
    }

    // get the membership service
    final MembershipService membership;
    try {
        membership = (MembershipService) namingContext
                .lookup(FactoryNamingConvention.getJNDINameForService(MembershipService.SERVICE_NAME));
    } catch (NamingException ne) {
        logger.error("Cannot manage to access Factory membership service. Caused by: ", ne);
        return false;
    }

    // create a login context
    LoginContext loginContext;
    try {
        loginContext = new LoginContext("qualipso", new UsernamePasswordHandler(username, password));
        loginContext.login();
    } catch (LoginException le) {
        logger.error("Cannot manage to use the login context. Caused by: ", le);
        return false;
    }

    // test if the login context is valid by trying to call the membership service
    final String profilePath;
    try {
        profilePath = membership.getProfilePathForConnectedIdentifier();
        logger.info("Profile path for user " + username + ": " + profilePath);
    } catch (EJBAccessException no) {
        // login is invalid
        logger.info("Login failed for user " + username);
        return false;
    }

    // if we're here, the login is valid. Put it in the session.
    session = getThreadLocalRequest().getSession();
    session.setAttribute(USERNAME_SESSION_ATTRIBUTE, username);
    session.setAttribute(PASSWORD_SESSION_ATTRIBUTE, password);
    logger.info("User " + username + " logged in, with profile path " + profilePath);

    // log out
    try {
        loginContext.logout();
    } catch (LoginException le) {
        // just log, don't do anything else
        logger.error("Problem logging out after testing correct login. Caused by: ", le);
    }

    return true;
}