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:de.ingrid.server.security.IngridRealm.java

@Override
public Principal authenticate(final String userName, final Object password, final Request request) {

    Principal principal = null;/* ww w . j ava2  s  .  c  o m*/
    try {
        final RequestCallbackHandler handler = new RequestCallbackHandler(request);
        final LoginContext loginContext = new LoginContext("IngridLogin", handler);
        loginContext.login();
        final Subject subject = loginContext.getSubject();
        final Set<Principal> principals = subject.getPrincipals();
        final Principal tmpPrincipal = principals.isEmpty() ? principal : principals.iterator().next();
        if (tmpPrincipal instanceof KnownPrincipal) {
            final KnownPrincipal knownPrincipal = (KnownPrincipal) tmpPrincipal;
            knownPrincipal.setLoginContext(loginContext);
            principal = knownPrincipal;
            LOG.info("principal has logged in: " + principal);
        }
    } catch (final LoginException e) {
        LOG.error("login error for user: " + userName);
    }
    if (principal == null) {
        LOG.info("login failed for userName: " + userName);
    }
    return principal;
}

From source file:com.tethrnet.manage.util.ExternalAuthUtil.java

/**
 * external auth login method//from   w  w w  .  j  a va2 s  .  com
 *
 * @param auth contains username and password
 * @return auth token if success
 */
public static String login(final Auth auth) {

    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername())
            && StringUtils.isNotEmpty(auth.getPassword())) {

        Connection con = null;
        try {
            CallbackHandler handler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            };

            try {
                LoginContext loginContext = new LoginContext(JAAS_MODULE, handler);
                //will throw exception if login fail
                loginContext.login();
                Subject subject = loginContext.getSubject();

                con = DBUtils.getConn();
                User user = AuthDB.getUserByUID(con, auth.getUsername());

                if (user == null) {
                    user = new User();

                    user.setUserType(User.ADMINISTRATOR);
                    user.setUsername(auth.getUsername());

                    //set email
                    if (auth.getUsername().contains("@")) {
                        user.setEmail(auth.getUsername());
                    }

                    user.setId(UserDB.insertUser(con, user));
                }

                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                //set auth token
                AuthDB.updateLogin(con, user);

            } catch (LoginException e) {
                //auth failed return empty
                authToken = null;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;
}

From source file:com.keybox.manage.util.ExternalAuthUtil.java

/**
 * external auth login method//from   www  .j av  a 2s  .c om
 *
 * @param auth contains username and password
 * @return auth token if success
 */
public static String login(final Auth auth) {

    String authToken = null;
    if (externalAuthEnabled && auth != null && StringUtils.isNotEmpty(auth.getUsername())
            && StringUtils.isNotEmpty(auth.getPassword())) {

        Connection con = null;
        try {
            CallbackHandler handler = new CallbackHandler() {

                @Override
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback callback : callbacks) {
                        if (callback instanceof NameCallback) {
                            ((NameCallback) callback).setName(auth.getUsername());
                        } else if (callback instanceof PasswordCallback) {
                            ((PasswordCallback) callback).setPassword(auth.getPassword().toCharArray());
                        }
                    }
                }
            };

            try {
                LoginContext loginContext = new LoginContext(JAAS_MODULE, handler);
                //will throw exception if login fail
                loginContext.login();
                Subject subject = loginContext.getSubject();

                con = DBUtils.getConn();
                User user = AuthDB.getUserByUID(con, auth.getUsername());

                if (user == null) {
                    user = new User();

                    user.setUserType(User.ADMINISTRATOR);
                    user.setUsername(auth.getUsername());

                    //if it looks like name is returned default it 
                    for (Principal p : subject.getPrincipals()) {
                        if (p.getName().contains(" ")) {
                            String[] name = p.getName().split(" ");
                            if (name.length > 1) {
                                user.setFirstNm(name[0]);
                                user.setLastNm(name[name.length - 1]);
                            }
                        }
                    }

                    //set email
                    if (auth.getUsername().contains("@")) {
                        user.setEmail(auth.getUsername());
                    }

                    user.setId(UserDB.insertUser(con, user));
                }

                authToken = UUID.randomUUID().toString();
                user.setAuthToken(authToken);
                user.setAuthType(Auth.AUTH_EXTERNAL);
                //set auth token
                AuthDB.updateLogin(con, user);

            } catch (LoginException e) {
                //auth failed return empty
                authToken = null;
            }
        } catch (Exception e) {
            log.error(e.toString(), e);
        }

        DBUtils.closeConn(con);
    }

    return authToken;
}

From source file:org.simbasecurity.core.chain.authentication.JaasLoginCommand.java

@Override
public State execute(ChainContext context) throws Exception {
    String userName = context.getUserName();
    try {// w  ww.ja va  2s. c  o m
        LoginContext loginContext = new LoginContext(getLoginConfEntry(),
                new ChainContextCallbackHandler(context));
        loginContext.login();

        credentialService.resetInvalidLoginCount(userName);

        logSuccess(context, AuditMessages.JAAS_LOGIN_SUCCESS);

        return State.CONTINUE;
    } catch (LoginException e) {
        logFailure(context, AuditMessages.JAAS_LOGIN_FAILED);

        if (credentialService.checkUserStatus(userName, Status.ACTIVE)) {
            boolean blocked = credentialService.increaseInvalidLoginCountAndBlockAccount(userName);
            if (blocked) {
                logFailure(context, AuditMessages.ACCOUNT_BLOCKED);
            }
        }

        context.redirectWithCredentialError(LOGIN_FAILED);
        return State.FINISH;
    }
}

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 {/*w w  w  .j a  va2 s  .  co m*/
            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:com.mycompany.kerberosbyip.NewMain.java

private void runPrivileged() throws Exception {
    final CallbackHandler handler = new ProvidedAuthCallback(username, password);
    final LoginContext lc = new LoginContext("KrbLogin", handler);
    lc.login();//from   w w  w.  j a v  a 2s. c o  m

    PrivilegedAction<Void> sendAction = new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            try {
                doSendRequest();
                return null;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

        }
    };

    Subject.doAs(lc.getSubject(), sendAction);
}

From source file:info.magnolia.cms.security.SecuritySupportBase.java

protected static LoginContext createLoginContext(CredentialsCallbackHandler callbackHandler,
        String customLoginModule) throws LoginException {
    final String loginContextName = StringUtils.defaultString(customLoginModule, DEFAULT_JAAS_LOGIN_CHAIN);
    return new LoginContext(loginContextName, callbackHandler);
}

From source file:br.mdarte.exemplo.academico.accessControl.LoginController.java

public final boolean verificarLogin(ActionMapping mapping, VerificarLoginForm form, HttpServletRequest request,
        HttpServletResponse response, HttpServlet servlet) throws Exception {
    EntrarLoginValidarFormImpl formLogin = null;
    String login = null;//w  ww . j  av a2 s .c om
    String senha = null;
    try {
        formLogin = (EntrarLoginValidarFormImpl) form;
        login = formLogin.getLogin();
        senha = formLogin.getSenha();
    } catch (Exception e) {
        senha = request.getParameter(ATTR_SENHA);
        login = request.getParameter(ATTR_LOGIN);
    }
    LoginContext loginCtx = null;
    ControleAcesso controleAcesso = new ControleAcessoImpl();
    try {
        if (controleAcesso.usuarioBloqueado(login)) {
            saveErrorMessage(request, "usuario.bloqueado");
            return false;
        }
        CallbackHandler handler = new LoginCallbackHandler(login, senha);
        loginCtx = new LoginContext("sistemaacademico", handler);
        loginCtx.login();
        Subject subject = loginCtx.getSubject();
        accessControl.SecurityHolder.setSubject(subject);
        PrincipalImpl principal = ControleAcesso.getCallerPrincipal(subject);
        principal.setNomeProjeto("sistemaacademico");
        request.getSession().setAttribute(Constantes.USER_SESSION, subject);
        String nome = principal.getOperador().getNomeIdentificadorMenu();
        request.getSession().setAttribute("nomeIdentificadorMenu", nome);
        posLogin(principal.getOperador(), request);
        return true;
    } catch (LoginException le) {
        if (le.getMessage().equals("Password Incorrect/Password Required")) {
            saveErrorMessage(request, "senha.incorreta");
        } else if (le.getMessage().equals("No matching username found in Principals")) {
            saveErrorMessage(request, "usuario.incorreto");
        } else {
            saveErrorMessage(request, le.getMessage());
        }
        return false;
    }
}

From source file:de.ingrid.admin.security.IngridRealm.java

@Override
public Principal authenticate(String userName, Object password, Request request) {

    Principal principal = null;/*from  w w w  . ja  v a  2 s  . c o  m*/
    try {
        RequestCallbackHandler handler = new RequestCallbackHandler(request);
        String[] url = request.getRequestURL().toString().split("/base/auth/j_security_check");
        // remember redirect url to jump to after initialization
        request.getSession().setAttribute("redirectUrl",
                request.getSession().getAttribute("org.mortbay.jetty.URI"));
        // automatically redirect to the welcome page, which initialize plug description into session
        request.getSession().setAttribute("org.mortbay.jetty.URI", url[0].concat("/base/welcome.html"));
        LoginContext loginContext = new LoginContext("IngridLogin", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();
        Set<Principal> principals = subject.getPrincipals();
        Principal tmpPrincipal = principals.isEmpty() ? principal : principals.iterator().next();
        if (tmpPrincipal instanceof KnownPrincipal) {
            KnownPrincipal knownPrincipal = (KnownPrincipal) tmpPrincipal;
            knownPrincipal.setLoginContext(loginContext);
            principal = knownPrincipal;
            LOG.info("principal has logged in: " + principal);
        }
    } catch (LoginException e) {
        LOG.error("login error for user: " + userName, e);
    }
    if (principal == null) {
        LOG.info("login failed for userName: " + userName);
    }
    return principal;
}

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

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

    try {/*from www  .  j  a v  a  2  s . com*/

        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());
        }
    }
}