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:info.magnolia.cms.security.Authenticator.java

/**
 * Authenticate authorization request using JAAS login module as configured
 * @param request as received by the servlet engine
 * @return boolean/*from  www. jav a  2  s. c  o m*/
 */
public static boolean authenticate(HttpServletRequest request) {
    String credentials = request.getHeader("Authorization");
    String userid;
    String pswd;
    CredentialsCallbackHandler callbackHandler;
    String loginModuleToInitialize = "magnolia"; // default login module

    if (StringUtils.isEmpty(credentials) || credentials.length() <= 6) {
        // check for form based login request
        if (StringUtils.isNotEmpty(request.getParameter(PARAMETER_USER_ID))) {
            userid = request.getParameter(PARAMETER_USER_ID);
            pswd = StringUtils.defaultString(request.getParameter(PARAMETER_PSWD));
            callbackHandler = new PlainTextCallbackHandler(userid, pswd.toCharArray());
        } else {
            // select login module to use if user is authenticated against the container
            if (request.getUserPrincipal() != null) {
                loginModuleToInitialize = "magnolia_authorization";
                callbackHandler = new PlainTextCallbackHandler(request.getUserPrincipal().getName(),
                        "".toCharArray());
            } else {
                // invalid auth request
                return false;
            }
        }
    } else {
        // its a basic authentication request
        callbackHandler = new Base64CallbackHandler(credentials);
    }

    Subject subject;
    try {
        LoginContext loginContext = new LoginContext(loginModuleToInitialize, callbackHandler);
        loginContext.login();
        subject = loginContext.getSubject();
        // ok, we NEED a session here since the user has been authenticated
        HttpSession httpsession = request.getSession(true);
        httpsession.setAttribute(ATTRIBUTE_JAAS_SUBJECT, subject);
    } catch (LoginException le) {
        if (log.isDebugEnabled())
            log.debug("Exception caught", le);

        HttpSession httpsession = request.getSession(false);
        if (httpsession != null) {
            httpsession.invalidate();
        }
        return false;
    }

    return true;
}

From source file:net.sf.jpam.jaas.LoginContextTest.java

/**
 * Checks that we can login.//  w  w  w.j a  va 2s .co m
 * <p/>
 * In this test, login is successful and commit is called.
 * @throws LoginException
 */
public void testLoginContext() throws LoginException {
    LoginContext loginContext;
    loginContext = new LoginContext("net-sf-jpam", new JpamCallbackHandler());
    loginContext.login();
}

From source file:org.jasig.cas.authentication.handler.support.JaasAuthenticationHandler.java

protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredentials credentials)
        throws AuthenticationException {

    final String transformedUsername = getPrincipalNameTransformer().transform(credentials.getUsername());

    try {/*from  www  . j a va  2s . c  om*/
        if (log.isDebugEnabled()) {
            log.debug("Attempting authentication for: " + transformedUsername);
        }
        final LoginContext lc = new LoginContext(this.realm,
                new UsernamePasswordCallbackHandler(transformedUsername, credentials.getPassword()));

        lc.login();
        lc.logout();
    } catch (final LoginException fle) {
        if (log.isDebugEnabled()) {
            log.debug("Authentication failed for: " + transformedUsername);
        }
        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Authentication succeeded for: " + transformedUsername);
    }
    return true;
}

From source file:be.fedict.hsm.ws.impl.JAASSOAPHandler.java

private void login(SOAPMessageContext context) throws LoginException, CertificateEncodingException {
    X509Certificate certificate = WSSecuritySOAPHandler.getAuthenticatedCertificate(context);
    byte[] encodedCertificate = certificate.getEncoded();
    NamePasswordCallbackHandler usernamePasswordHandler = new NamePasswordCallbackHandler(encodedCertificate);
    LoginContext loginContext = new LoginContext(ApplicationClientSecurityDomain.NAME, usernamePasswordHandler);
    context.put(LOGIN_CONTEXT_ATTRIBUTE, loginContext);
    loginContext.login();//from w w w.  j a  v  a 2 s.c om
}

From source file:net.sf.jpam.jaas.LoginContextTest.java

/**
 * Checks that specifying a service name:
 * 1) works//from w  w w. jav a  2  s .  co  m
 * 2) causes an error when the config is missing
 * <p/>
 * In this test, login is successful and commit is called.
 * @throws LoginException
 */
public void testLoginContextBadServiceName() {
    LoginContext loginContext;
    try {
        loginContext = new LoginContext("bad-service", new JpamCallbackHandler());
    } catch (LoginException e) {
        //expected
    }
}

From source file:com.hs.mail.imap.user.DefaultUserManager.java

/**
 * Authenticate the given user against the given password. When
 * authenticated, the ID of the user will be supplied.
 * //  w w  w  . j  ava 2 s  .  c  om
 * @param username
 *            user name
 * @param password
 *            password supplied
 * @return id of the user when authenticated
 * @throws LoginException
 *             when the user does not exist or not authenticated
 */
public long login(String username, String password) throws LoginException {
    String address = toAddress(username);
    User user = DaoFactory.getUserDao().getUserByAddress(address);
    if (user == null) {
        throw new AccountNotFoundException("Account for " + username + " not found");
    }
    if (Config.getAuthScheme() != null) {
        CallbackHandler callbackHandler = new BasicCallbackHandler(address, password.toCharArray());
        LoginContext lc = new LoginContext(Config.getAuthScheme(), callbackHandler);
        lc.login();
    } else {
        if (!password.equals(user.getPassword())) {
            throw new CredentialException("Incorrect password for " + username);
        }
    }
    return user.getID();
}

From source file:net.sf.jpam.jaas.LoginContextTest.java

/**
 * Checks what happens if a bad password is given
 * <p/>/* w ww . ja va 2s .co  m*/
 * In this test, login is unsuccessful and abort is called.
 * @throws LoginException
 */
public void testLoginContextBadPassword() throws LoginException {
    LoginContext loginContext;
    callbackCredentials = user1BadCredentials;
    loginContext = new LoginContext("net-sf-jpam", new JpamCallbackHandler());
    try {
        loginContext.login();
        fail();
    } catch (FailedLoginException e) {
        //
    }
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}/*w w w.ja v a 2s  .co  m*/
 */
public Subject login(final UserCredential pUserCredential) {
    try {
        final CallbackHandlerImpl callbackHandler = new CallbackHandlerImpl(pUserCredential);
        final LoginContext loginContext = new LoginContext(mLoginModuleName, callbackHandler);
        loginContext.login();
        final Subject subject = loginContext.getSubject();
        if (mStateManager != null && subject != null) {
            final RequestState requestState = new RequestState();
            requestState.setStateId(pUserCredential.getStateId());
            requestState.setSubject(subject);
            requestState.setUserName(pUserCredential.getUser());
            mStateManager.addRequestStateForToken(pUserCredential.getStateId(), requestState);
        }
        return subject;
    } catch (LoginException e) {
        throw new ServiceException(pUserCredential,
                "Failed to authenticate an user with the credentials - " + pUserCredential, e);
    }
}

From source file:com.teklabs.throng.integration.ldap.Ldap.java

/**
 * Checks password using GSSAPI./*from   w  w  w  .java2s . c  o  m*/
 *
 * @param principal principal
 * @param password  password
 * @return true, if principal can be authenticated with specified password
 */
private boolean checkPasswordUsingGssapi(String principal, String password) {
    // Use our custom configuration to avoid reliance on external config
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    LoginContext lc;
    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
        LdapHelper.LOG.debug("Password is not valid for principal: " + principal, e);
        return false;
    }
    try {
        lc.logout();
    } catch (LoginException e) {
        LdapHelper.LOG.warn("Logout fails", e);
    }
    return true;

}

From source file:com.cubusmail.server.services.CubusService.java

public void logout() throws Exception {

    try {/*www.j ava  2 s .  c  o  m*/
        LoginContext context = new LoginContext(MailboxLoginModule.class.getSimpleName(),
                SessionManager.get().getSubject());
        context.logout();
        SessionManager.invalidateSession();
    } catch (LoginException e) {
        log.error(e.getMessage(), e);
        throw new GWTLogoutException(e.getMessage());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}