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:com.cloudera.alfredo.client.KerberosAuthenticator.java

/**
 * Implements the SPNEGO authentication sequence interaction using the current default principal
 * in the Kerberos cache (normally set via kinit).
 *
 * @param token the authencation token being used for the user.
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *//*w w w.j a  v a 2s .  c o  m*/
private void doSpnegoSequence(AuthenticatedURL.Token token) throws IOException, AuthenticationException {
    try {
        AccessControlContext context = AccessController.getContext();
        Subject subject = Subject.getSubject(context);
        if (subject == null) {
            subject = new Subject();
            LoginContext login = new LoginContext("", subject);
            login.login();
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator.this.url.getHost();
                    GSSName serviceName = gssManager.createName(servicePrincipal,
                            GSSUtil.NT_GSS_KRB5_PRINCIPAL);
                    gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null,
                            GSSContext.DEFAULT_LIFETIME);
                    gssContext.requestCredDeleg(true);
                    gssContext.requestMutualAuth(true);

                    byte[] inToken = new byte[0];
                    byte[] outToken;
                    boolean established = false;

                    // Loop while the context is still not established
                    while (!established) {
                        outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                        if (outToken != null) {
                            sendToken(outToken);
                        }

                        if (!gssContext.isEstablished()) {
                            inToken = readToken();
                        } else {
                            established = true;
                        }
                    }
                } finally {
                    if (gssContext != null) {
                        gssContext.dispose();
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public void init(Properties config) throws ServletException {
    try {/*from w  w w .  j a va2s .  c  om*/
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        for (String spnegoPrincipal : spnegoPrincipals) {
            log.info("Login using keytab %s, for principal %s", keytab, spnegoPrincipal);
            final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration(
                    keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                log.warn(le, "Failed to login as [%s]", spnegoPrincipal);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

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 ww  .  ja  v  a  2  s  . co m
 * @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:com.cubusmail.server.services.CubusService.java

public GWTMailbox login(String username, String password) throws Exception {

    try {/* w ww  .  j a va2  s. c  om*/

        LoginContext context = new LoginContext(MailboxLoginModule.class.getSimpleName(),
                new MailboxCallbackHandler(username, password));

        context.login();

        // if no exception thrown, login was successful
        SessionManager.createSession(context.getSubject());

        IMailbox mailbox = SessionManager.get().getMailbox();

        UserAccount account = this.userAccountDao.getUserAccountByUsername(username);
        // create useraccount
        if (account == null) {
            account = createUserAccount(mailbox);
            if (getThreadLocalRequest().getLocale() != null) {
                String lang = getThreadLocalRequest().getLocale().getLanguage();
                account.getPreferences().setLanguage(lang);
            }
        } else {
            if (account.getIdentities() == null || account.getIdentities().size() == 0) {
                account.addIdentity(createDefaultIdentity(mailbox));
            }
            account.setLastLogin(new Date());
            this.userAccountDao.saveUserAccount(account);
        }

        mailbox.setUserAccount(account);
        GWTMailbox gwtMailbox = ConvertUtil.convert(mailbox);

        return gwtMailbox;
    } catch (LoginException e) {
        log.error(e.getMessage(), e);
        if (IErrorCodes.EXCEPTION_AUTHENTICATION_FAILED.equals(e.getMessage())) {
            throw new GWTAuthenticationException(e.getMessage());
        } else if (IErrorCodes.EXCEPTION_CONNECT.equals(e.getMessage())) {
            throw new GWTConnectionException(e.getMessage());
        } else {
            throw new GWTLoginException(e.getMessage());
        }
    }
}

From source file:org.springframework.security.kerberos.client.KerberosRestTemplate.java

@Override
protected final <T> T doExecute(final URI url, final HttpMethod method, final RequestCallback requestCallback,
        final ResponseExtractor<T> responseExtractor) throws RestClientException {

    try {//from   www  .  jav  a  2  s  . c  om
        LoginContext lc = buildLoginContext();
        lc.login();
        Subject serviceSubject = lc.getSubject();
        return Subject.doAs(serviceSubject, new PrivilegedAction<T>() {

            @Override
            public T run() {
                return KerberosRestTemplate.this.doExecuteSubject(url, method, requestCallback,
                        responseExtractor);
            }
        });

    } catch (Exception e) {
        throw new RestClientException("Error running rest call", e);
    }
}

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

/**
 * Checks password using GSSAPI./*from   www  . java  2 s  .  c  om*/
 *
 * @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.hs.mail.web.controller.WebConsole.java

private ModelAndView doLogin(WebSession session, String username, String password, String facility) {
    try {/*from   ww  w  .j  av a  2 s.c om*/
        CallbackHandler callbackHandler = new BasicCallbackHandler(username, password.toCharArray());
        LoginContext lc = new LoginContext(facility, callbackHandler);
        lc.login();
        session.storeBean(WebSession.LOGIN_CONTEXT, lc);
        List<String> domains = Arrays.asList(Config.getDomains());
        ModelAndView mav = new ModelAndView("console");
        mav.addObject("domains", domains);
        return mav;
    } catch (LoginException e) {
        logger.error(e.getMessage(), e);
        return new ModelAndView("index", "error", "incorrect.password");
    }
}

From source file:be.fedict.eid.applet.beta.webapp.JAASLoginFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    LOG.debug("doFilter");
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpSession httpSession = httpRequest.getSession();
    Credentials credentials = (Credentials) httpSession.getAttribute("org.jboss.seam.security.credentials");
    LoginContext loginContext = null;
    String username = credentials.getUsername();
    if (null != username) {
        CallbackHandler callbackHandler = new UsernamePasswordHandler(username, username);
        try {//from w w w .  java 2 s  .c  om
            loginContext = new LoginContext("client-login", callbackHandler);
            loginContext.login();
        } catch (LoginException e) {
            throw new ServletException("JAAS login error");
        }
    }
    try {
        chain.doFilter(request, response);
    } finally {
        if (null != loginContext) {
            try {
                loginContext.logout();
            } catch (LoginException e) {
                throw new ServletException("JAAS logout error");
            }
        }
    }
}

From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java

@Override
protected void handleRemoteLoginLive(String userName, String pass) throws Exception {
    UserHbm user;/* ww  w  . j a v  a2s .  c  om*/
    try {
        user = getUserHbmDao().load(userName);
    } catch (Exception ex) {
        throw new SecurityException("Invalid Principal");
    }

    user.setLoginDate((System.currentTimeMillis()));
    LoginContext lc = new LoginContext("juwimm-cms-security-domain",
            new CredentialCallbackHandler(userName, pass));
    lc.login();
    //UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user);
    //return ulv;
}

From source file:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java

@Override
protected UserLoginValue handleRemoteLogin(String userName, String pass) throws Exception {
    UserHbm user;/*from  w  ww  . j a  va2 s  .c o m*/
    try {
        user = getUserHbmDao().load(userName);
    } catch (Exception ex) {
        throw new SecurityException("Invalid Principal");
    }

    user.setLoginDate((System.currentTimeMillis()));
    LoginContext lc = new LoginContext("juwimm-cms-security-domain",
            new CredentialCallbackHandler(userName, pass));
    lc.login();
    UserLoginValue ulv = getUserHbmDao().getUserLoginValue(user);
    return ulv;
}