Example usage for javax.security.auth Subject Subject

List of usage examples for javax.security.auth Subject Subject

Introduction

In this page you can find the example usage for javax.security.auth Subject Subject.

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

From source file:org.apache.hadoop.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.
 *///  w  w w.  ja  v a2s  .  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, null, new KerberosConfiguration());
            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();
                    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:org.josso.jb5.agent.JOSSOJASPIAuthenticator.java

@Override
protected boolean authenticate(Request request, Response response, LoginConfig config) throws IOException {
    boolean result = false;

    String authMethod = config.getAuthMethod();

    // Have we already authenticated someone?
    Principal principal = request.getUserPrincipal();
    if (principal != null) {
        log.trace("Already authenticated '" + principal.getName() + "'");
        //return true;
    }//from   www  . java  2  s  .co m

    Realm realm = this.context.getRealm();
    // Is this request URI subject to a security constraint?
    SecurityConstraint[] constraints = realm.findSecurityConstraints(request, this.context);

    if (!jossoCookieExists(request) && principal == null && constraints != null && constraints.length > 0) {
        boolean authRequired = true;
        for (int i = 0; i < constraints.length && authRequired; i++) {
            if (!constraints[i].getAuthConstraint()) {
                authRequired = false;
            } else if (!constraints[i].getAllRoles()) {
                String[] roles = constraints[i].findAuthRoles();
                if (roles == null || roles.length == 0) {
                    authRequired = false;
                }
            }
        }

        if (authRequired) {
            forwardToLoginPage(request, response, config);
            return false;
        }
    }

    GenericMessageInfo messageInfo = new GenericMessageInfo();
    messageInfo.setRequestMessage(request);
    messageInfo.setResponseMessage(response);

    // Put bits of information needed by tomcat server auth modules
    messageInfo.getMap().put("CACHE", cache);

    JASPICallbackHandler cbh = new JASPICallbackHandler();

    Subject subject = new Subject();
    ServerAuthenticationManager sam = getServerAuthenticationManager();
    if (sam != null) {
        result = sam.isValid(messageInfo, subject, messageLayer, cbh);
    }

    // The Authentication process has been a success. We need to register
    // the principal, username, password with the container
    if (result) {
        PasswordValidationCallback pvc = cbh.getPasswordValidationCallback();
        CallerPrincipalCallback cpcb = cbh.getCallerPrincipalCallback();
        if (pvc != null && cpcb != null) {
            this.register(request, response, cpcb.getPrincipal(), authMethod, pvc.getUsername(),
                    new String(pvc.getPassword()));
            JBossSecurityAssociationActions.setPrincipalInfo(cpcb.getPrincipal(), new String(pvc.getPassword()),
                    subject);
        }
    }

    return result;
}

From source file:org.jcommon.com.util.jmx.RmiAdptor.java

public void setCserver(MBeanServer server) throws MalformedURLException, IOException {
    if (port == 0 || name == null || addr == null) {
        throw new NullPointerException("data not be ready");
    }/*from w  w w .j av a  2 s. co m*/
    try {
        registry = LocateRegistry.createRegistry(port);
    } catch (RemoteException e) {

    }
    HashMap<String, Object> prop = new HashMap<String, Object>();
    if (CREDENTIALS != null) {
        authenticator = new JMXAuthenticator() {

            public Subject authenticate(Object credentials) {
                logger.info(credentials.getClass().getName() + " is trying connect...");
                if (credentials instanceof String) {
                    if (credentials.equals(CREDENTIALS)) {
                        return new Subject();
                    }
                } else if (credentials instanceof String[]) {
                    String[] copy = (String[]) credentials;
                    String username = copy.length > 0 ? copy[0] : null;
                    String passwd = copy.length > 1 ? copy[1] : null;
                    logger.info(username + " is trying connect...");
                    if (passwd.equals(CREDENTIALS) && username.equals(user)) {
                        return new Subject();
                    }
                }
                throw new SecurityException("not authicated");
            }
        };

        prop.put(JMXConnectorServer.AUTHENTICATOR, authenticator);
    }
    String url = "service:jmx:rmi:///jndi/rmi://" + addr + ":" + port + "/" + name;
    this.cserver = JMXConnectorServerFactory.newJMXConnectorServer(new JMXServiceURL(url), prop, server);
}

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 av 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:org.apache.karaf.jaas.modules.krb5.Krb5LoginModuleTest.java

@Test
public void testKeytabSuccess() throws Exception {

    Map<String, Object> props = new HashMap<>();
    props.put("debug", "true");
    props.put("useKeyTab", "true");
    props.put("keyTab", createKeytab());
    props.put("principal", "hnelson@EXAMPLE.COM");
    props.put("doNotPrompt", "true");
    props.put("storeKey", "true");
    props.put("detailed.login.exception", "true");

    Subject subject = new Subject();

    Krb5LoginModule module = new Krb5LoginModule();
    module.initialize(subject, null, null, props);

    assertEquals("Precondition", 0, subject.getPrincipals().size());

    Assert.assertTrue(module.login());/*from   w  w  w  .j av  a2s  . c  o  m*/
    Assert.assertTrue(module.commit());

    assertEquals(1, subject.getPrincipals().size());

    boolean foundUser = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundUser = true;
            break;
        }
    }
    assertTrue(foundUser);

    boolean foundToken = false;
    for (Object crd : subject.getPrivateCredentials()) {
        if (crd instanceof KerberosTicket) {
            assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
            assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
            foundToken = true;
            break;
        }
    }
    assertTrue(foundToken);

    Assert.assertTrue(module.logout());

}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.ShibbolethSSOTestCase.java

protected ShibbolethSSOLoginContext buildLoginContext() {
    Principal principal = new UsernamePrincipal("test");

    Subject subject = new Subject();
    subject.getPrincipals().add(principal);

    AuthenticationMethodInformation authnInfo = new AuthenticationMethodInformationImpl(subject, principal,
            "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified", new DateTime(), 3600);

    ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
    loginContext.setAuthenticationMethodInformation(authnInfo);
    loginContext.setPrincipalAuthenticated(true);
    loginContext.setRelyingParty("urn:example.org:sp1");
    loginContext.setSpAssertionConsumerService("https://example.org/mySP");
    loginContext.setSpTarget("https://example.org/mySP");

    return loginContext;
}

From source file:org.josso.jb4.agent.JBossCatalinaNativeRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the Gateway
 * as the authenticatd Principal.//w  w  w.  j ava 2  s  .c o m
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

            Group callerPrincipal = new BaseRoleImpl("CallerPrincipal");
            callerPrincipal.addMember(ssoUser);
            // Add the "CallerPrincipal" group to the Subject so that JBoss can fetch user.
            subject.getPrincipals().add(callerPrincipal);

            logger.debug("Authenticated Subject: " + subject);

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = rm.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal);

            // Get the caching principal
            principal = getCachingPrincpal(rm, oldPrincipal, principal, credentials, subject);

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the Gateway
 * as the authenticatd Principal.//from ww w  . ja  v  a 2 s . c  om
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

            logger.debug("Authenticated Subject: " + subject);

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = rm.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal);
            if (!principal.equals(oldPrincipal)) {
                _userPrincipalMap.put(principal, oldPrincipal);
            }

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2SSOTestCase.java

protected Saml2LoginContext buildLoginContext(String relyingPartyId) throws Exception {
    Principal principal = new UsernamePrincipal("test");

    Subject subject = new Subject();
    subject.getPrincipals().add(principal);

    AuthenticationMethodInformation authnInfo = new AuthenticationMethodInformationImpl(subject, principal,
            "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified", new DateTime(), 3600);

    AuthnRequest request = buildAuthnRequest(relyingPartyId);

    Saml2LoginContext loginContext = new Saml2LoginContext(relyingPartyId, null, request);
    loginContext.setAuthenticationMethodInformation(authnInfo);
    loginContext.setPrincipalAuthenticated(true);
    loginContext.setRelyingParty(relyingPartyId);

    return loginContext;
}

From source file:fi.okm.mpass.idp.authn.impl.SocialUserAuthServletTest.java

protected SocialRedirectAuthenticator initSubjectAuthenticator() throws Exception {
    SocialRedirectAuthenticator authenticator = Mockito.mock(SocialRedirectAuthenticator.class);
    Subject subject = new Subject();
    subject.getPrincipals().add(new UsernamePrincipal(username));
    Mockito.when(authenticator.getSubject((HttpServletRequest) Mockito.any())).thenReturn(subject);
    return authenticator;
}