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.juwimm.cms.test.hibernate.HbmTestImpl.java

public void loginUser(String username, String password) {
    Principal p = null;/*w w w .  j a  v a  2  s .  co m*/
    if (loginContext == null) {
        SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler(username, password);
        try {
            loginContext = new LoginContext("juwimm-cms-security-domain", simpleCallbackHandler);
            loginContext.login();
            Subject s = loginContext.getSubject();
            Iterator it = s.getPrincipals().iterator();
            if (!s.getPrincipals().isEmpty()) {
                while (it.hasNext()) {
                    p = (Principal) it.next();
                    if (!p.getName().equalsIgnoreCase(SYSTEM_USER)) {
                        org.andromda.spring.PrincipalStore.set(p);
                        break;
                    }
                }
            }
        } catch (LoginException e) {
            if (log.isErrorEnabled()) {
                log.error("Could not login: " + e.getMessage(), e);
            }
        }
    }
}

From source file:de.juwimm.cms.beans.foreign.security.ConQuestDaoAuthenticationProvider.java

/**
 * Attempts to login the user given the Authentication objects principal and credential
 *
 * @param auth The Authentication object to be authenticated.
 *
 * @return The authenticated Authentication object, with it's grantedAuthorities set.
 *
 * @throws AuthenticationException This implementation does not handle 'locked' or 'disabled' accounts. This method
 *         only throws a AuthenticationServiceException, with the message of the LoginException that will be
 *         thrown, should the loginContext.login() method fail.
 *///from w  ww.j av  a 2 s  . c  o m
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth instanceof UsernamePasswordAuthenticationToken) {
        UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) auth;

        try {
            //Create the LoginContext object, and pass our InternallCallbackHandler
            LoginContext loginContext = new LoginContext(loginContextName, new InternalCallbackHandler(auth));

            //Attempt to login the user, the LoginContext will call our InternalCallbackHandler at this point.
            loginContext.login();

            //create a set to hold the authorities, and add any that have already been applied.
            Set authorities = new HashSet();

            if (request.getAuthorities() != null) {
                authorities.addAll(Arrays.asList(request.getAuthorities()));
            }

            //get the subject principals and pass them to each of the AuthorityGranters
            Set principals = loginContext.getSubject().getPrincipals();

            authorities.add(new JaasGrantedAuthority("*", new AllPrincipal()));

            for (Iterator iterator = principals.iterator(); iterator.hasNext();) {
                Principal principal = (Principal) iterator.next();
                if (principal instanceof Group) {
                    Group g = (Group) principal;
                    if (g.members() != null) {
                        Enumeration members = g.members();
                        while (members.hasMoreElements()) {
                            Principal object = (Principal) members.nextElement();
                            authorities.add(new JaasGrantedAuthority(object.toString(), object));
                        }
                    } else {
                        authorities.add(new JaasGrantedAuthority(g.toString(), g));
                    }
                }
            }

            //Convert the authorities set back to an array and apply it to the token.
            JaasAuthenticationToken result = new JaasAuthenticationToken(request.getPrincipal(),
                    request.getCredentials(),
                    (GrantedAuthority[]) authorities.toArray(new GrantedAuthority[authorities.size()]),
                    loginContext);

            //Publish the success event
            publishSuccessEvent(result);

            //we're done, return the token.
            return result;
        } catch (LoginException loginException) {
            SpringSecurityException ase = loginExceptionResolver.resolveException(loginException);

            publishFailureEvent(request, ase);
            throw ase;
        }
    }

    return null;
}

From source file:com.hs.mail.web.controller.WebConsole.java

private ModelAndView doLogin(WebSession session, String username, String password, String facility) {
    try {/* w w  w  .  j ava 2 s  .c o m*/
        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:de.juwimm.cms.test.hibernate.HbmTestImpl.java

public Principal loginSystemUser() {
    Principal p = null;//from  www  .  j  a v a 2s  . c om
    if (loginContext == null) {
        log.info("Setting principal...");
        //TODO login         
        //         System.setProperty( "java.security.auth.login.config", "C:\\svnroot\\juwimm-cms\\core\\src\\test\\jaas.conf" );
        String encoded = "e";
        SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler(SYSTEM_USER, encoded);
        try {
            loginContext = new LoginContext("juwimm-cms-security-domain", simpleCallbackHandler);
            loginContext.login();
            Subject s = loginContext.getSubject();
            Iterator it = s.getPrincipals().iterator();
            if (!s.getPrincipals().isEmpty()) {
                p = (Principal) it.next();
                org.andromda.spring.PrincipalStore.set(p);
            }
        } catch (LoginException e) {

            if (log.isErrorEnabled()) {
                log.error("Could not login: " + e.getMessage(), e);
            }
        }
    }
    return p;
}

From source file:org.apache.brooklyn.security.StockSecurityProviderTest.java

private LoginContext doLogin(final String username, final String password) throws LoginException {
    assertRealmRegisteredEventually(WEBCONSOLE_REALM);
    LoginContext lc = new LoginContext(WEBCONSOLE_REALM, new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                Callback callback = callbacks[i];
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(password.toCharArray());
                } else if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(username);
                }//from   ww  w .jav  a2 s .  c o m
            }
        }
    });
    lc.login();
    return lc;
}

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.
 *//*from   w w  w.  j  a  va2 s .  c om*/
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:com.telefonica.iot.cygnus.backends.http.HttpBackend.java

private JsonResponse doPrivilegedRequest(String method, String url, ArrayList<Header> headers,
        StringEntity entity) throws CygnusRuntimeError {
    try {/*from ww  w .  j  a  va2  s.  c  om*/
        LoginContext loginContext = new LoginContext("cygnus_krb5_login",
                new KerberosCallbackHandler(krb5User, krb5Password));
        loginContext.login();
        PrivilegedRequest req = new PrivilegedRequest(method, url, headers, entity);
        return createJsonResponse((HttpResponse) Subject.doAs(loginContext.getSubject(), req));
    } catch (LoginException e) {
        throw new CygnusRuntimeError("Privileged request error", "LoginException", e.getMessage());
    } // try catch
}

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

/**
 * @see de.juwimm.cms.authorization.remote.AuthorizationServiceSpring#login(java.lang.String,
 *      java.lang.String, java.lang.Integer)
 *//*w  w w.j av a2s. c  o  m*/
@Override
protected UserLoginValue handleLogin(String userName, String passwd, Integer siteId) throws Exception {
    // try {
    if (log.isDebugEnabled()) {
        log.debug("Try to login \"" + AuthenticationHelper.getUserName() + "\" at " + siteId);
    }

    SiteHbm site = null;
    try {
        site = super.getSiteHbmDao().load(siteId);
    } catch (Exception exe) {
        throw new SecurityException("Invalid SiteId");
    }
    UserHbm user = null;

    try {
        user = super.getUserHbmDao().load(AuthenticationHelper.getUserName());
    } catch (Exception ex) {
        throw new SecurityException("Invalid Principal");
    }
    if (!user.isMasterRoot() && !user.getSites().contains(site)) {
        throw new SecurityException("User is not a member of the given site!");
    }
    user.setActiveSite(site);
    user.setLoginDate((System.currentTimeMillis()));
    LoginContext lc = new LoginContext("juwimm-cms-security-domain", new InternalCallbackHandler(passwd));
    lc.login();
    /*
     * if(log.isDebugEnabled()) { Subject subj = lc.getSubject();
     * Principal[] prip = (Principal[]) subj.getPrincipals().toArray(new
     * Principal[0]); Group groupPrincipal = null; for(int i = 0; i <
     * prip.length; i++) { if(prip[i] instanceof Group) { groupPrincipal =
     * ((Group) prip[i]); Enumeration group = groupPrincipal.members();
     * while(group.hasMoreElements()) { Principal rolePrincipal =
     * ((Principal) group.nextElement()); String role =
     * rolePrincipal.getName(); log.debug("User is in role: " + role); } }
     * else { //log.warn("Found one Principal other then a group - is is: " +
     * prip[i].getName()); } } }
     */
    if (log.isInfoEnabled())
        log.info("Login User " + user.getUserId() + " at site " + site.getSiteId() + " ("
                + site.getShortName().trim() + ")");
    // UserLoginValue ulv = user.getUserLoginValue();
    UserLoginValue ulv = super.getUserHbmDao().getUserLoginValue(user);
    ulv.setSiteName(site.getName());
    ulv.setSiteConfigXML(site.getConfigXML());
    return ulv;
    // } catch (Exception e) {
    // throw new UserException(e.getMessage());
    // }
}

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request//from w  ww  .  j  a  v a  2 s . co  m
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

    /**
     * Guard clause to check for the unsupported NTLM authentication mechanism.
     */
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return false;
    }

    /**
     * The server attempts to establish a security context. Establishment may result in tokens that the server must return to the client. Tokens are BASE-64 encoded
     * GSS-API data.
     */
    GSSContext gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the "context initiator." In the case of the Kerberos mechanism, the context initiator is
     * the Kerberos principal of the client. Additionally, the client may be delegating credentials.
     */
    if (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            /**
             * A status code 200 status response can also carry a "WWW-Authenticate" response header containing the final leg of an authentication. In this case, the
             * gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an authentication error. If a 401 containing a "WWW-Authenticate" header with "Negotiate" and
         * gssapi-data is returned from the server, it is a continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}