Example usage for javax.security.auth Subject getPrincipals

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

Introduction

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

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAuthorizedRepositoriesAreTheSameFoundInSubject() {

    Subject subject = new Subject();

    String identity = "testuser";
    subject.getPrincipals().add(new IdentityPrincipal(identity));

    Group group = new CmsGroup(AstroboaPrincipalName.AuthorizedRepositories.toString());
    group.addMember(new CmsPrincipal("testRepositoryA"));
    group.addMember(new CmsPrincipal("testRepositoryB"));
    group.addMember(new CmsPrincipal(TestConstants.TEST_REPOSITORY_ID));

    subject.getPrincipals().add(group);/*from  w w w .j a v a 2  s.c  om*/

    repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, null);

    SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();

    Assert.assertNotNull(securityContext, "Found no security context in Thread for logged in user " + identity);

    List<String> authorizedRepositories = securityContext.getAuthorizedRepositories();

    Assert.assertTrue(CollectionUtils.isNotEmpty(authorizedRepositories),
            "Authorized repositories must not be empty");

    Assert.assertTrue(authorizedRepositories.size() == 3,
            "Authorized repositories must be exactly 3. " + authorizedRepositories.toString());

    for (String repositoryId : authorizedRepositories) {
        Assert.assertTrue(
                repositoryId.equals("testRepositoryA") || repositoryId.equals("testRepositoryB")
                        || repositoryId.equals(TestConstants.TEST_REPOSITORY_ID),
                "Repository id " + repositoryId + " must not exist in authorized repositories "
                        + authorizedRepositories.toString());
    }

}

From source file:org.betaconceptframework.astroboa.test.engine.service.RepositoryServiceTest.java

@Test
public void testLoginPermanentKey() {

    String permanentKey = "fakeKey";

    //Connect to test repository with fake key
    try {/* w  w  w . j a  v  a 2  s.c om*/
        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        Assert.assertEquals(1, 2, "Login succeded with false key");
    } catch (Exception e) {
        Assert.assertEquals(e.getMessage(),
                "Invalid permanent key " + permanentKey + " for user " + TestConstants.TEST_USER_NAME
                        + " in repository " + TestConstants.TEST_REPOSITORY_ID,
                "Login did not take place with false key nevertheless exception is thrown " + e.getMessage());
    }

    //Connect with correct key
    permanentKey = "keyForTest";
    try {
        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID,
                new AstroboaCredentials(TestConstants.TEST_USER_NAME, "betaconcept".toCharArray()),
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Connect with anonymous using subject
    permanentKey = "specialKey";
    try {

        Subject subject = new Subject();
        subject.getPrincipals().add(new IdentityPrincipal("anonymous"));

        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject,
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Connect with * using subject
    permanentKey = "globalKey";
    try {

        Subject subject = new Subject();
        subject.getPrincipals().add(new IdentityPrincipal("anyUser"));

        authenticationToken = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);

        //Connect again and check that authentication token is the same
        String authenticationToken2 = repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject,
                permanentKey);

        Assert.assertEquals(authenticationToken, authenticationToken2,
                "Login with trusted keys produced two different authentication tokens");

    } catch (Exception e) {
        throw new CmsException(e);
    }

    //Back to normal
    loginToTestRepositoryAsTestUser();
    cmsRepositoryEntityFactory = CmsRepositoryEntityFactoryForActiveClient.INSTANCE.getFactory();

}

From source file:org.apache.hadoop.hbase.thrift.TestThriftSpnegoHttpServer.java

private CloseableHttpClient createHttpClient() throws Exception {
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(clientPrincipal, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());

    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);//from w  w w . ja va  2s.c  om

    // The name of the principal
    final String clientPrincipalName = clientPrincipals.iterator().next().getName();

    return Subject.doAs(clientSubject, new PrivilegedExceptionAction<CloseableHttpClient>() {
        @Override
        public CloseableHttpClient run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(clientPrincipalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME,
                    oid, GSSCredential.INITIATE_ONLY);

            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

            return HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry)
                    .setDefaultCredentialsProvider(credentialsProvider).build();
        }
    });
}

From source file:org.artificer.devsvr.ArtificerDevServer.java

/**
 * @return a security handler//from  w w w  . j  a v a 2s.c o  m
 */
private SecurityHandler createSecurityHandler(boolean forUI) {
    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[] { "user" });
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setSessionRenewedOnAuthentication(false);
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("artificer");
    if (forUI) {
        csh.addConstraintMapping(cm);
    }
    csh.setLoginService(new HashLoginService() {
        @Override
        public UserIdentity login(String username, Object credentials) {
            Credential credential = (credentials instanceof Credential) ? (Credential) credentials
                    : Credential.getCredential(credentials.toString());
            Principal userPrincipal = new KnownUser(username, credential);
            Subject subject = new Subject();
            subject.getPrincipals().add(userPrincipal);
            subject.getPrivateCredentials().add(credential);
            String[] roles = new String[] { "user", "readonly", "readwrite", "admin" };
            for (String role : roles) {
                subject.getPrincipals().add(new RolePrincipal(role));
            }
            subject.setReadOnly();
            return _identityService.newUserIdentity(subject, userPrincipal, roles);
        }
    });

    return csh;
}

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;/* w  w w  .  ja  va2s . c o m*/

    try {
        // 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:org.apache.ws.security.spnego.SpnegoTokenContext.java

/**
 * Validate a service ticket./* w w w  . j  ava2 s  .c  om*/
 * @param jaasLoginModuleName
 * @param callbackHandler
 * @param serviceName
 * @param ticket
 * @throws WSSecurityException
 */
public void validateServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler,
        String serviceName, byte[] ticket) throws WSSecurityException {
    // Get a TGT from the KDC using JAAS
    LoginContext loginContext = null;
    try {
        if (callbackHandler == null) {
            loginContext = new LoginContext(jaasLoginModuleName);
        } else {
            loginContext = new LoginContext(jaasLoginModuleName, callbackHandler);
        }
        loginContext.login();
    } catch (LoginException ex) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(ex.getMessage(), ex);
        }
        throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                new Object[] { ex.getMessage() }, ex);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully authenticated to the TGT");
    }

    // Get the service name to use - fall back on the principal
    Subject subject = loginContext.getSubject();
    String service = serviceName;
    if (service == null) {
        Set<Principal> principals = subject.getPrincipals();
        if (principals.isEmpty()) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError",
                    new Object[] { "No Client principals found after login" });
        }
        service = principals.iterator().next().getName();
    }

    // Validate the ticket
    serviceAction.setTicket(ticket);
    serviceAction.setServiceName(service);
    token = (byte[]) Subject.doAs(subject, serviceAction);

    secContext = serviceAction.getContext();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Successfully validated a service ticket");
    }

}

From source file:org.globus.axis.handler.CredentialHandler.java

public void invoke(MessageContext msgContext) throws AxisFault {
    log.debug("Enter: invoke");

    Object tmp = msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);

    if ((tmp == null) || !(tmp instanceof HttpServletRequest)) {
        return;//from  w  w w  .j av a2  s . co m
    }

    HttpServletRequest req = (HttpServletRequest) tmp;

    // if httpg is access protocol in servlet engine, axis
    // will not set the TRANS_URL property correctly.
    // this is a workaround for that problem
    String url = req.getRequestURL().toString();
    tmp = msgContext.getProperty(MessageContext.TRANS_URL);
    if (tmp == null && url != null) {
        msgContext.setProperty(MessageContext.TRANS_URL, url);
    }

    Subject subject = getSubject(msgContext);

    // USER_DN is set by both HTTPS/HTTPG valves
    tmp = req.getAttribute(GSIConstants.GSI_USER_DN);
    if (tmp != null) {
        msgContext.setProperty(GSIConstants.GSI_USER_DN, tmp);
        subject.getPrincipals().add(new GlobusPrincipal((String) tmp));
    }

    // GSI_CONTEXT is set by HTTPS valve only
    tmp = req.getAttribute(GSIConstants.GSI_CONTEXT);
    if (tmp != null) {
        msgContext.setProperty(GSIConstants.GSI_CONTEXT, tmp);
        GSSContext ctx = (GSSContext) tmp;
        try {
            if (ctx.getDelegCred() != null) {
                subject.getPrivateCredentials().add(ctx.getDelegCred());
            }
        } catch (GSSException e) {
            log.warn("Unable to obtain delegated credentials", e);
        }
    }

    // GSI_CREDENTIALS is set only by HTTPG valve
    tmp = req.getAttribute(GSIConstants.GSI_CREDENTIALS);
    if (tmp != null) {
        log.debug("Delegation performed. Setting credentials property.");
        msgContext.setProperty(GSIConstants.GSI_CREDENTIALS, tmp);
        subject.getPrivateCredentials().add(tmp);
    } else {
        log.debug("Delegation not performed. Not setting credentials property.");
    }

    // GSI_AUTH_USERNAM is set only by HTTPG Valve
    tmp = req.getAttribute(GSIConstants.GSI_AUTH_USERNAME);
    if (tmp != null) {
        msgContext.setProperty(GSIConstants.GSI_AUTH_USERNAME, tmp);
        subject.getPrincipals().add(new UserNamePrincipal((String) tmp));
    }

    log.debug("Exit: invoke");
}

From source file:org.apache.hadoop.hbase.http.TestSpnegoHttpServer.java

@Test
public void testAllowedClient() throws Exception {
    // Create the subject for the client
    final Subject clientSubject = JaasKrbUtil.loginUsingKeytab(CLIENT_PRINCIPAL, clientKeytab);
    final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
    // Make sure the subject has a principal
    assertFalse(clientPrincipals.isEmpty());

    // Get a TGT for the subject (might have many, different encryption types). The first should
    // be the default encryption type.
    Set<KerberosTicket> privateCredentials = clientSubject.getPrivateCredentials(KerberosTicket.class);
    assertFalse(privateCredentials.isEmpty());
    KerberosTicket tgt = privateCredentials.iterator().next();
    assertNotNull(tgt);//  ww w  .  j  a v  a2s  .co m

    // The name of the principal
    final String principalName = clientPrincipals.iterator().next().getName();

    // Run this code, logged in as the subject (the client)
    HttpResponse resp = Subject.doAs(clientSubject, new PrivilegedExceptionAction<HttpResponse>() {
        @Override
        public HttpResponse run() throws Exception {
            // Logs in with Kerberos via GSS
            GSSManager gssManager = GSSManager.getInstance();
            // jGSS Kerberos login constant
            Oid oid = new Oid("1.2.840.113554.1.2.2");
            GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
            GSSCredential credential = gssManager.createCredential(gssClient, GSSCredential.DEFAULT_LIFETIME,
                    oid, GSSCredential.INITIATE_ONLY);

            HttpClientContext context = HttpClientContext.create();
            Lookup<AuthSchemeProvider> authRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                    .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, true)).build();

            HttpClient client = HttpClients.custom().setDefaultAuthSchemeRegistry(authRegistry).build();
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential));

            URL url = new URL(getServerURL(server), "/echo?a=b");
            context.setTargetHost(new HttpHost(url.getHost(), url.getPort()));
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthSchemeRegistry(authRegistry);

            HttpGet get = new HttpGet(url.toURI());
            return client.execute(get, context);
        }
    });

    assertNotNull(resp);
    assertEquals(HttpURLConnection.HTTP_OK, resp.getStatusLine().getStatusCode());
    assertEquals("a:b", EntityUtils.toString(resp.getEntity()).trim());
}

From source file:org.wso2.carbon.andes.authorization.service.andes.QpidAuthorizationPlugin.java

/**
* Authorize operations inside broker/*from www  . j av  a 2  s  .co m*/
* 
* @param operation
*               Operation on broker object (CONSUME, PUBLISH, etc)
* @param objectType
*               Type of object (EXCHANGE, QUEUE, etc)
* @param properties
*               Properties attached to the operation 
* @return
*               ALLOWED/DENIED 
*/
public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) {
    try {

        // Get username from tenant username
        PrivilegedCarbonContext.startTenantFlow();
        Subject subject = SecurityManager.getThreadSubject();

        Principal principal = null;
        if (subject != null) {
            principal = (Principal) (subject.getPrincipals().toArray())[0];
        }

        if (principal == null) { // No user associated with the thread
            return getDefault();
        }

        String username = principal.getName();

        // Get User Realm
        UserRealm userRealm = getUserRealm(username);

        if (username.indexOf(DOMAIN_NAME_SEPARATOR) > -1) {
            String tenantDomain = username.substring(username.indexOf(DOMAIN_NAME_SEPARATOR) + 1);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantId(MultitenantConstants.SUPER_TENANT_ID);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        }

        int domainNameSeparatorIndex = username.indexOf(DOMAIN_NAME_SEPARATOR);
        if (-1 != domainNameSeparatorIndex) {
            username = username.substring(0, domainNameSeparatorIndex);
        }
        switch (operation) {
        case CREATE:
            if (ObjectType.EXCHANGE == objectType) {
                return Result.ALLOWED;
            } else if (ObjectType.QUEUE == objectType) {
                return QpidAuthorizationHandler.handleCreateQueue(username, userRealm, properties);
            }
        case BIND:
            return QpidAuthorizationHandler.handleBindQueue(username, userRealm, properties);
        case PUBLISH:
            return QpidAuthorizationHandler.handlePublishToExchange(username, userRealm, properties);
        case CONSUME:
            return QpidAuthorizationHandler.handleConsumeQueue(username, userRealm, properties);
        case UNBIND:
            return QpidAuthorizationHandler.handleUnbindQueue(properties);
        case DELETE:
            if (ObjectType.EXCHANGE == objectType) {
                return Result.ALLOWED;
            } else if (ObjectType.QUEUE == objectType) {
                return QpidAuthorizationHandler.handleDeleteQueue(username, userRealm, properties);
            }
        }
    } catch (Exception e) {
        logger.error("Error while invoking QpidAuthorizationHandler", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return Result.DENIED;
}

From source file:org.wso2.carbon.andes.authorization.service.andes.AndesAuthorizationPlugin.java

/**
 * Authorize operations inside broker//from w ww  .  ja v a2s.c o  m
 *
 * @param operation  Operation on broker object (CONSUME, PUBLISH, etc)
 * @param objectType Type of object (EXCHANGE, QUEUE, etc)
 * @param properties Properties attached to the operation
 * @return ALLOWED/DENIED
 */
public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) {
    try {

        // Get username from tenant username
        PrivilegedCarbonContext.startTenantFlow();
        Subject subject = SecurityManager.getThreadSubject();

        Principal principal = null;
        if (subject != null) {
            principal = (Principal) (subject.getPrincipals().toArray())[0];
        }

        if (principal == null) { // No user associated with the thread
            return getDefault();
        }

        String username = principal.getName();

        if (username.contains(DOMAIN_NAME_SEPARATOR)) {
            String tenantDomain = username.substring(username.indexOf(DOMAIN_NAME_SEPARATOR) + 1);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
            PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
        } else {
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantId(MultitenantConstants.SUPER_TENANT_ID);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        }

        // Get User Realm
        UserRealm userRealm = getUserRealm(username);

        int domainNameSeparatorIndex = username.indexOf(DOMAIN_NAME_SEPARATOR);
        if (-1 != domainNameSeparatorIndex) {
            username = username.substring(0, domainNameSeparatorIndex);
        }
        switch (operation) {
        case CREATE:
            if (ObjectType.EXCHANGE == objectType) {
                return Result.ALLOWED;
            } else if (ObjectType.QUEUE == objectType) {
                return AndesAuthorizationHandler.handleCreateQueue(username, userRealm, properties);
            }
        case BIND:
            return AndesAuthorizationHandler.handleBindQueue(username, userRealm, properties);
        case PUBLISH:
            return AndesAuthorizationHandler.handlePublishToExchange(username, userRealm, properties);
        case CONSUME:
            return AndesAuthorizationHandler.handleConsumeQueue(username, userRealm, properties);
        case BROWSE:
            return AndesAuthorizationHandler.handleBrowseQueue(username, userRealm, properties);
        case UNBIND:
            return AndesAuthorizationHandler.handleUnbindQueue(properties);
        case DELETE:
            if (ObjectType.EXCHANGE == objectType) {
                return Result.ALLOWED;
            } else if (ObjectType.QUEUE == objectType) {
                return AndesAuthorizationHandler.handleDeleteQueue(username, userRealm, properties);
            }
        case PURGE:
            return AndesAuthorizationHandler.handlePurgeQueue(username, userRealm, properties);
        }
    } catch (AndesAuthorizationHandlerException e) {
        logger.error("Error while invoking AndesAuthorizationHandler", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }

    return Result.DENIED;
}