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:de.juwimm.cms.authorization.remote.AuthorizationServiceSpringImpl.java

/**
 * @see de.juwimm.cms.authorization.remote.AuthorizationServiceSpring#login(java.lang.String,
 *      java.lang.String, java.lang.Integer)
 *///ww w.  ja v a 2 s  .  co 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:org.apache.cxf.fediz.integrationtests.KerberosTest.java

private String getEncodedKerberosTicket(boolean spnego) throws Exception {

    System.setProperty("java.security.auth.login.config", "src/test/resources/kerberos.jaas");
    System.setProperty("org.apache.xml.security.ignoreLineBreaks", "true");

    Oid kerberos5Oid = null;
    if (spnego) {
        kerberos5Oid = new Oid("1.3.6.1.5.5.2");
    } else {//from w  ww  .  j a  va  2  s.  c  om
        kerberos5Oid = new Oid("1.2.840.113554.1.2.2");
    }

    GSSManager manager = GSSManager.getInstance();
    GSSName serverName = manager.createName("bob@service.ws.apache.org", GSSName.NT_HOSTBASED_SERVICE);

    GSSContext context = manager.createContext(serverName.canonicalize(kerberos5Oid), kerberos5Oid, null,
            GSSContext.DEFAULT_LIFETIME);

    context.requestCredDeleg(true);

    final byte[] token = new byte[0];

    String contextName = "alice";
    LoginContext lc = new LoginContext(contextName);
    lc.login();

    byte[] ticket = (byte[]) Subject.doAs(lc.getSubject(), new CreateServiceTicketAction(context, token));
    return Base64.encode(ticket);
}

From source file:com.lucidworks.security.authentication.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 authentication token being used for the user.
 *
 * @throws IOException if an IO error occurred.
 * @throws AuthenticationException if an authentication error occurred.
 *///from  w  w w .ja v a 2 s .  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) {
            LOG.debug("No subject in context, logging in");
            subject = new Subject();
            LoginContext login = new LoginContext("", subject, null, new KerberosConfiguration());
            login.login();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Using subject: " + subject);
        }
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = KerberosUtil.getServicePrincipal("HTTP",
                            KerberosAuthenticator.this.url.getHost());
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, 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();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

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

public Subject login(String login, String senha) {
    LoginContext loginContext = null;
    try {//from   w w w.j  a  v a2 s. c  o m
        CallbackHandler handler = new LoginCallbackHandler(login, senha);
        loginContext = new LoginContext("sistemaacademico", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();
        accessControl.SecurityHolder.setSubject(subject);
        PrincipalImpl principal = getCallerPrincipal(subject);
        principal.setNomeProjeto("sistemaacademico");

        return subject;

    } catch (LoginException e) {
        System.err.println(e.getMessage());
        return null;
    }
}

From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java

/**
 * Authenticate a received service request.
 * <p/>/*from  w  ww. jav a  2s  .  c o  m*/
 * This method is called to transform the mechanism-specific request message
 * acquired by calling getRequestMessage (on messageInfo) into the validated
 * application message to be returned to the message processing runtime. If
 * the received message is a (mechanism-specific) meta-message, the method
 * implementation must attempt to transform the meta-message into a
 * corresponding mechanism-specific response message, or to the validated
 * application request message. The runtime will bind a validated
 * application message into the the corresponding service invocation.
 * <p>
 * This method conveys the outcome of its message processing either by
 * returning an AuthStatus value or by throwing an AuthException.
 * <p/>
 * From a performance point of view this method will be called twice for
 * each resource with a security constraint on it. Resources with no
 * security constraint do not result in a call to this method.
 * 
 * @param messageInfo
 *            A contextual object that encapsulates the client request and
 *            server response objects, and that may be used to save state
 *            across a sequence of calls made to the methods of this
 *            interface for the purpose of completing a secure message
 *            exchange.
 * @param clientSubject
 *            A Subject that represents the source of the service request.
 *            It is used by the method implementation to store Principals
 *            and credentials validated in the request.
 * @param serviceSubject
 *            A Subject that represents the recipient of the service
 *            request, or null. It may be used by the method implementation
 *            as the source of Principals or credentials to be used to
 *            validate the request. If the Subject is not null, the method
 *            implementation may add additional Principals or credentials
 *            (pertaining to the recipient of the service request) to the
 *            Subject.
 * @return An AuthStatus object representing the completion status of the
 *         processing performed by the method. The AuthStatus values that
 *         may be returned by this method are defined as follows:
 *         <p/>
 *         <ul>
 *         <li>AuthStatus.SUCCESS when the application request message was
 *         successfully validated. The validated request message is
 *         available by calling getRequestMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_SUCCESS to indicate that
 *         validation/processing of the request message successfully
 *         produced the secured application response message (in
 *         messageInfo). The secured response message is available by
 *         calling getResponseMessage on messageInfo.
 *         <p/>
 *         <li>AuthStatus.SEND_CONTINUE to indicate that message validation
 *         is incomplete, and that a preliminary response was returned as
 *         the response message in messageInfo.
 *         <p/>
 *         When this status value is returned to challenge an application
 *         request message, the challenged request must be saved by the
 *         authentication module such that it can be recovered when the
 *         module's validateRequest message is called to process the request
 *         returned for the challenge.
 *         <p/>
 *         <li>AuthStatus.SEND_FAILURE to indicate that message validation
 *         failed and that an appropriate failure response message is
 *         available by calling getResponseMessage on messageInfo.
 *         </ul>
 * @throws AuthException When the message processing failed without
 *         establishing a failure response message (in messageInfo).
 */
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject)
        throws AuthException {
    // Get the servlet context
    final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    final HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    final String auth = request.getHeader(AUTHORIZATION_HEADER);
    // Test prefix for HTTP BASIC Auth
    if (auth != null && StringUtils.startsWithIgnoreCase(auth, "basic ")) {
        // We might have a valid header, so try to decode it
        final String data = new String(Base64.decodeBase64(auth.substring(BASIC_PREFIX_LENGTH)), UTF_8);
        final int splitIndex = data.indexOf(':');
        if (splitIndex < 0) {
            return sendErrorAndAuthenticateRequest(request, response, "Wrong WWW-Authenticate header format");
        }
        final String username = data.substring(splitIndex);
        final char[] password = data.substring(splitIndex + 1, data.length()).toCharArray();

        // Prepare the JAAS callback to feed any LoginModule with user and password
        final NameCallback nameCallback = new NameCallback("username");
        nameCallback.setName(username);

        final PasswordCallback passwordCallback = new PasswordCallback(getRealm(request), false);
        passwordCallback.setPassword(password);

        final CallbackHandler delegatedHandler = new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                for (int i = 0; i < callbacks.length; i++) {
                    final Callback c = callbacks[i];
                    if (c instanceof NameCallback) {
                        ((NameCallback) c).setName(username);
                    } else if (c instanceof PasswordCallback) {
                        ((PasswordCallback) c).setPassword(password);
                    } else {
                        throw new UnsupportedOperationException(
                                String.format("Callback type %s (%s) is not supported yet.", c.getClass(), c));
                    }
                }
            }
        };

        if (this.jaasContextName == null) {
            throw new UnsupportedOperationException(
                    "No delegate JAAS context found. As per JASPIC JAAS Bridge profile, this parameter is requiered.");
        }

        try {
            // Create a new JAAS context with the delegated data & try to login
            final LoginContext context = new LoginContext(this.jaasContextName, delegatedHandler);
            context.login();

            // Get the authenticated subject from the JAAS context
            Subject authenticatedSubject = context.getSubject();

            final PasswordValidationCallback passwordValidationCallback = new PasswordValidationCallback(
                    authenticatedSubject, username, password);

            // notify JASPIC containerr for the name, password and subject
            this.handler.handle(new Callback[] { passwordValidationCallback });

        } catch (final LoginException ex) {
            // If there was any issue during the JAAS login, fail the process
            final AuthException aex = new AuthException(
                    String.format("Fail to login user %s with the delegated JAAS context %s", username,
                            this.jaasContextName));
            aex.initCause(ex);
        } catch (final IOException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        } catch (final UnsupportedCallbackException e) {
            LOG.log(Level.WARNING, "Unable to call the handlers for name=" + nameCallback, e);
        }

    } else if (this.mandatory) {
        return sendErrorAndAuthenticateRequest(request, response,
                "AuthModule was mandatory but no valid credential was provided");
    } else {
        LOG.info("No authentication was provided bu Basic AuthModule is not mandatory so return SUCCESS.");
    }

    return AuthStatus.SUCCESS;
}

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 {/*w ww.  ja v  a2s . c  o  m*/
        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.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.
 *//*w w w .  j a v 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.qut.middleware.esoe.authn.plugins.spnego.authenticator.KerberosV5Authenticator.java

@SuppressWarnings("unchecked")
private String loginAndAction(String loginContextName, KerberosAuthenticationAction actionToPerform) {
    LoginContext context = null;

    try {//from w  ww  .  j a  v  a2 s .  co  m
        // Create a LoginContext 
        context = new LoginContext(loginContextName, null, null, this.config);

        this.logger.trace(Messages.getString("KerberosV5Authenticator.7") + loginContextName); //$NON-NLS-1$

        // Perform server authentication
        context.login();

        Subject subject = context.getSubject();
        this.logger.trace(subject.toString());
        this.logger.trace(Messages.getString("KerberosV5Authenticator.8") + subject.getPrincipals()); //$NON-NLS-1$

        // perform kerberos validation
        return (String) (Subject.doAs(subject, actionToPerform));

    } catch (LoginException e) {
        this.logger.warn(Messages.getString("KerberosV5Authenticator.9")); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    } catch (PrivilegedActionException e) {
        this.logger.trace(e.getLocalizedMessage(), e);
        this.logger.trace(Messages.getString("KerberosV5Authenticator.10") + e.getCause().getMessage()); //$NON-NLS-1$

        return null;
    } catch (Exception e) {
        this.logger.debug(Messages.getString("KerberosV5Authenticator.11") + e.getCause().getMessage()); //$NON-NLS-1$
        this.logger.trace(e.getLocalizedMessage(), e);

        return null;
    }

}

From source file:com.flipkart.fdp.migration.distcp.security.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * /*from   ww  w  .  j a  v  a2  s .  c o m*/
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
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, null, new KerberosConfiguration());
         * login.login(); }
         */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        // if (LOG.isDebugEnabled()) {
        // LOG.debug("Kerberos authenticated user: "
        // + loginContext.getSubject());
        // }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    String sp = KerberosAuthenticator2.this.servicePrincipal;
                    if (sp == null) {
                        sp = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    }
                    GSSName serviceName = gssManager.createName(sp, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, 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();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}

From source file:main.client.http.KerberosAuthenticator2.java

/**
 * Implements the SPNEGO authentication sequence interaction using the
 * current default principal in the Kerberos cache (normally set via kinit).
 * //from w  w  w  . j  a  v  a2  s .  c  om
 * @param token
 *            the authentication token being used for the user.
 * 
 * @throws IOException
 *             if an IO error occurred.
 * @throws AuthenticationException
 *             if an authentication error occurred.
 */
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, null,
          new KerberosConfiguration());
                    login.login();
                 }
        */

        LoginContext loginContext = new LoginContext("", null,
                new KerberosClientCallbackHandler(username, password), new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: " + loginContext.getSubject());
        }
        Subject subject = loginContext.getSubject();

        Subject.doAs(subject, new PrivilegedExceptionAction<Void>() {

            @Override
            public Void run() throws Exception {
                GSSContext gssContext = null;
                try {
                    GSSManager gssManager = GSSManager.getInstance();
                    String servicePrincipal = "HTTP/" + KerberosAuthenticator2.this.url.getHost();
                    Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                    GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                    oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                    gssContext = gssManager.createContext(serviceName, 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();
                        gssContext = null;
                    }
                }
                return null;
            }
        });
    } catch (PrivilegedActionException ex) {
        throw new AuthenticationException(ex.getException());
    } catch (LoginException ex) {
        throw new AuthenticationException(ex);
    }
    AuthenticatedURL.extractToken(conn, token);
}