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

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

Introduction

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

Prototype

public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException 

Source Link

Document

Instantiate a new LoginContext object with a name and a CallbackHandler object.

Usage

From source file:org.rhq.enterprise.server.auth.SubjectManagerBean.java

private void _checkAuthentication(String username, String password) throws LoginException {
    try {// w  w w.j av a  2 s .  com
        UsernamePasswordHandler handler = new UsernamePasswordHandler(username, password.toCharArray());
        LoginContext loginContext;
        loginContext = new LoginContext(CustomJaasDeploymentServiceMBean.SECURITY_DOMAIN_NAME, handler);

        loginContext.login();
        loginContext.getSubject().getPrincipals().iterator().next();
        loginContext.logout();
    } catch (javax.security.auth.login.LoginException e) {
        throw new LoginException(e.getMessage());
    }
}

From source file:org.rhq.enterprise.server.core.jaas.DelegatingLoginModule.java

@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState,
        Map<String, ?> options) {

    debugEnabled = LOG.isDebugEnabled();

    super.initialize(subject, callbackHandler, sharedState, options);

    /* This is the login context (=security domain) we want to delegate to */
    String delegateTo = (String) options.get("delegateTo");

    /* Comma separated list of roles that should be set for the principal */
    String additionalRoles = (String) options.get("roles");
    rolesList = StringUtil.explode(additionalRoles, ",");

    if (delegateTo == null || delegateTo.isEmpty()) {
        delegateTo = "other";
        LOG.warn("module-option 'delegateTo' was not set. Defaults to 'other'.");
    }/*from  w ww .  j a  v  a 2 s  .  c  o m*/

    if (debugEnabled) {
        LOG.debug("Delegating to " + delegateTo + " with roles " + additionalRoles);
    }

    // Now create the context for later use
    try {
        loginContext = new LoginContext(delegateTo, new DelegateCallbackHandler());
    } catch (LoginException e) {
        LOG.warn("Initialize failed : " + e.getMessage());
    }
}

From source file:org.sakaiproject.component.kerberos.user.JassAuthenticate.java

public boolean attemptAuthentication(String username, String password) {
    LoginContext userLoginContext = null;
    LoginContext serverLoginContext = null;

    try {//from  w  w  w .ja v  a  2  s  .  c  o m
        // This may well fail so run catch exceptions here.
        try {
            userLoginContext = new LoginContext(userPrincipal,
                    new UsernamePasswordCallback(username, password));
            userLoginContext.login();
        } catch (LoginException le) {
            if (log.isDebugEnabled()) {
                log.debug("Failed to authenticate " + username, le);
            }
            return false;
        }
        if (!verifyServiceTicket) {
            log.debug("Authenticated ok and not attempting service ticket verification");
            return true;
        }
        // Shouldn't ever fail
        serverLoginContext = new LoginContext(servicePrincipal, new NullCallbackHandler());
        serverLoginContext.login();

        GSSManager manager = GSSManager.getInstance();
        Oid kerberos = new Oid("1.2.840.113554.1.2.2");

        GSSName serverName = manager.createName(serverGSS, GSSName.NT_HOSTBASED_SERVICE);

        clientContext = manager.createContext(serverName, kerberos, null, GSSContext.DEFAULT_LIFETIME);

        serverContext = manager.createContext((GSSCredential) null);

        int exchanges = 0;
        while (!clientContext.isEstablished() && !serverContext.isEstablished()
                && !(initTokens == null && acceptTokens == null)) {
            Subject.doAs(userLoginContext.getSubject(), new InitiatorAction());
            Subject.doAs(serverLoginContext.getSubject(), new AcceptorAction());
            if (++exchanges > exchangeLimit) {
                throw new RuntimeException("Too many tickets exchanged (" + exchangeLimit + ").");
            }
        }
        log.debug("Authenticated ok and verified service ticket");
        return true;
    } catch (GSSException gsse) {
        log.warn("Failed to verify ticket.", gsse);
    } catch (LoginException le) {
        log.warn("Failed to login with keytab.", le);
    } finally {
        try {
            if (clientContext != null)
                clientContext.dispose();
            if (serverContext != null)
                serverContext.dispose();

            if (userLoginContext != null)
                userLoginContext.logout();
            if (serverLoginContext != null)
                serverLoginContext.logout();
        } catch (Exception e) {
            log.error("Failed to tidy up after attempting authentication.", e);
        }
    }
    return false;
}

From source file:org.sakaiproject.component.kerberos.user.KerberosUserDirectoryProvider.java

/**
 * Check if the user id is known to kerberos.
 * /*from ww w  . j a v  a 2  s .  c om*/
 * @param user
 *        The user id.
 * @return true if successful, false if not.
 */
private boolean userKnownToKerberos(String user) {
    // use a dummy password
    String pw = "dummy";

    // Obtain a LoginContext, needed for authentication.
    // Tell it to use the LoginModule implementation specified
    // in the JAAS login configuration file and to use
    // use the specified CallbackHandler.
    LoginContext lc = null;
    try {
        CallbackHandler t = new UsernamePasswordCallback(user, pw);
        lc = new LoginContext(m_logincontext, t);
    } catch (LoginException le) {
        if (M_log.isDebugEnabled())
            M_log.debug("useKnownToKerberos(): " + le.toString());
        return false;
    } catch (SecurityException se) {
        if (M_log.isDebugEnabled())
            M_log.debug("useKnownToKerberos(): " + se.toString());
        return false;
    }

    try {
        // attempt authentication
        lc.login();
        lc.logout();

        if (M_log.isDebugEnabled())
            M_log.debug("useKnownToKerberos(" + user + "): Kerberos auth success");

        return true;
    } catch (LoginException le) {
        String msg = le.getMessage();

        // if this is the message, the user was good, the password was bad
        if (msg.startsWith(m_knownusermsg)) {
            if (M_log.isDebugEnabled())
                M_log.debug("userKnownToKerberos(" + user + "): Kerberos user known (bad pw)");

            return true;
        }

        // the other message is when the user is bad:
        if (M_log.isDebugEnabled())
            M_log.debug("userKnownToKerberos(" + user + "): Kerberos user unknown or invalid");

        return false;
    }

}

From source file:org.sonar.plugins.ldap.LdapAuthenticator.java

private boolean checkPasswordUsingGssapi(String principal, String password, String ldapKey) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;//from  w  w w .j  ava 2  s . c o m
    try {
        lc = new LoginContext(getClass().getName(), new CallbackHandlerImpl(principal, password));
        lc.login();
    } catch (LoginException e) {
        // Bad username: Client not found in Kerberos database
        // Bad password: Integrity check on decrypted field failed
        LOG.debug("Password not valid for {} in server {}: {}", principal, ldapKey, e.getMessage());
        return false;
    }
    try {
        lc.logout();
    } catch (LoginException e) {
        LOG.warn("Logout fails", e);
    }
    return true;
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {/*  w w  w  .ja  v  a2  s  .c  o  m*/
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}

From source file:org.springframework.security.authentication.jaas.JaasAuthenticationProvider.java

@Override
protected LoginContext createLoginContext(CallbackHandler handler) throws LoginException {
    return new LoginContext(getLoginContextName(), handler);
}

From source file:org.wso2.carbon.identity.application.authenticator.iwa.IWAAuthenticationUtil.java

/**
 * Create server credential using SPNName and SPNPassword. This credential is used to decrypt the Kerberos Token
 * presented by the user. Although an actual authentication does not happen with the KDC, an invalid password
 * will result in checksum failure when decrypting the token.
 *
 * @param callbackHandler username password callback handler
 * @throws PrivilegedActionException/*from  w  w w  .ja va  2 s.  c o m*/
 * @throws LoginException
 */
private static GSSCredential createServerCredentials(CallbackHandler callbackHandler)
        throws PrivilegedActionException, LoginException {
    LoginContext loginContext = new LoginContext(IWAConstants.SERVER, callbackHandler);
    loginContext.login();

    if (log.isDebugEnabled()) {
        log.debug("Pre-authentication successful for with Kerberos Server.");
    }
    // create server credentials from pre authentication with the AD
    return createCredentialsForSubject(loginContext.getSubject());
}