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:AuthenticateNT.java

public static void main(String[] args) {
    try {//w  w  w.j  a  va  2s .c  o  m
        LoginContext loginContext = new LoginContext("AuthenticateNT");
        loginContext.login();
        System.out.println("Login Successful");
        Subject subject = loginContext.getSubject();
        System.out.println(subject);
        Subject.doAs(subject, new WriteFileAction());
        loginContext.logout();
        System.exit(0);
    } catch (LoginException loginException) {
        loginException.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.vmware.identity.openidconnect.client.GSSTestUtils.java

static GSSNegotiationHandler getKerberosNegotiationHandler() throws GSSException, LoginException, IOException {
    getProperties();/*from w  w w . j  ava 2s  .  co m*/
    final javax.security.auth.Subject jaasSubject = new javax.security.auth.Subject();
    GSSContext context = createGSSContext(spn);
    GSSNegotiationHandler handler = new GssNegotiationHandler(jaasSubject, context);

    LoginContext login = getLoginCtx(principal, password, jaasSubject);
    login.login();

    return handler;
}

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

/**
 * external auth login method/* w ww .  j av a2 s . c o  m*/
 *
 * @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: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 ww  w  .j a v  a 2 s.  co  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:com.keybox.manage.util.ExternalAuthUtil.java

/**
 * external auth login method/*from w  ww. java 2 s  .  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: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();

    PrivilegedAction<Void> sendAction = new PrivilegedAction<Void>() {
        @Override//  w  w  w .j  a  v a  2  s.  c  o  m
        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

@Override
public LoginResult authenticate(CredentialsCallbackHandler callbackHandler, String customLoginModule) {
    Subject subject;//from w w  w  .  ja v a 2 s  .c o  m
    try {
        LoginContext loginContext = createLoginContext(callbackHandler, customLoginModule);
        loginContext.login();
        subject = loginContext.getSubject();

        return new LoginResult(LoginResult.STATUS_SUCCEEDED, subject);
    } catch (LoginException e) {
        logLoginException(e);
        return new LoginResult(LoginResult.STATUS_FAILED, e);
    }
}

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.  ja  v a 2s  .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:de.ingrid.admin.security.IngridRealm.java

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

    Principal principal = null;/*  w  ww  . j  a v a 2  s.  com*/
    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:org.simbasecurity.core.chain.authentication.JaasLoginCommand.java

@Override
public State execute(ChainContext context) throws Exception {
    String userName = context.getUserName();
    try {//from  ww w.j  av a 2  s  . c  om
        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;
    }
}