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.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java

@Test
public void testLogin() throws LoginException {
    LoginContext context = new LoginContext("PropertiesLogin", new UserPassHandler("first", "secret"));

    context.login();/*from  www.  j a va 2 s . c  om*/

    Subject subject = context.getSubject();

    assertEquals("Should have three principals", 3, subject.getPrincipals().size());
    assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size());
    assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size());

    context.logout();

    assertEquals("Should have zero principals", 0, subject.getPrincipals().size());
}

From source file:fi.csc.mobileauth.shibboleth.rest.MobileServiceLoginHandler.java

public static Subject getResponse(String loginContextKey) {
    if (communicationDataStore.containsKey(loginContextKey)) {
        Map<String, String> attributes = communicationDataStore.getData(loginContextKey).getAttributes();
        if (attributes == null) {
            log.warn("No response attributes found for {} to be returned", loginContextKey);
            return null;
        }//from  w w  w .  jav  a2 s . c  o m
        log.debug("List of attributes size {}", attributes.size());
        final Subject userSubject = new Subject();
        String mobileNumber = attributes.get(StatusResponse.ATTRIBUTE_ID_MSISDN);
        if (mobileNumber == null) {
            log.warn("Could not obtain mobile number from the response attributes for {}", loginContextKey);
            return null;
        }
        String hookAttribute = DatatypeHelper
                .safeTrimOrNullString(attributes.get(userIdentifierResolver.getHookAttributeName()));
        if (hookAttribute == null) {
            log.debug("Populating the attributes to the Principal objects");
            return populatePrincipals(userSubject, attributes, mobileNumber);
        }
        String username = userIdentifierResolver.getUserIdentifier(hookAttribute);
        log.debug("Resolved username {} to mobile number {}", username, mobileNumber);
        if (username != null) {
            userSubject.getPrincipals().add(new UsernamePrincipal(username));
        } else {
            userSubject.getPrincipals().add(new MobileNumberPrincipal(mobileNumber));
        }
        return userSubject;
    }
    log.warn("No data stored for {}, could not return response object", loginContextKey);
    return null;
}

From source file:org.wso2.andes.server.security.access.plugins.AccessControl.java

/**
 * Check if an operation is authorised by asking the  configuration object about the access
 * control rules granted to the current thread's {@link Subject}. If there is no current
 * user the plugin will abstain.//from  ww  w . ja v  a  2  s .  c  o m
 */
public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) {
    final Subject subject = SecurityManager.getThreadSubject();
    // Abstain if there is no subject/principal associated with this thread
    if (subject == null || subject.getPrincipals().size() == 0) {
        return Result.ABSTAIN;
    }

    return _ruleSet.check(subject, operation, objectType, properties);
}

From source file:backtype.storm.security.auth.kerberos.KerberosSaslTransportPlugin.java

private String getPrincipal(Subject subject) {
    Set<Principal> principals = (Set<Principal>) subject.getPrincipals();
    if (principals == null || principals.size() < 1) {
        LOG.info("No principal found in login subject");
        return null;
    }/*from w  w  w. j  ava  2  s . c om*/
    return ((Principal) (principals.toArray()[0])).getName();
}

From source file:org.josso.auth.scheme.NtlmAuthSchemeTest.java

public void testNtlmAuth() throws Exception {
    log.debug("geting bean NtlmAuthScheme...");
    NtlmAuthScheme scheme = (NtlmAuthScheme) applicationContext.getBean("josso-ntlm-authentication");
    assert scheme != null : "No authentication scheme configured";

    Credential domainCredential = scheme.newCredential(NtlmCredentialProvider.DOMAIN_CONTROLLER_CREDENTIAL,
            UniAddress.getByName("130.5.5.233"));
    Credential passCredential = scheme.newCredential(NtlmCredentialProvider.PASSWORD_AUTHENTICATION_CREDENTIAL,
            new NtlmPasswordAuthentication("NT-DOMAIN", "Administrator", "novascope"));
    Subject s = new Subject();
    scheme.initialize(new Credential[] { domainCredential, passCredential }, s);

    scheme.authenticate();/*  w ww. j  a v  a 2 s.  co  m*/
    scheme.confirm();

    assert s.getPrincipals().size() == 1 : "Expected one principal, got : " + s.getPrincipals().size();

    Principal user = s.getPrincipals().iterator().next();
    assert user.getName().equals("Administrator") : "Expected Administrator principal, got : " + user.getName();
}

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

@Test
public void testIdentity() throws Exception {
    Subject subject = new Subject();

    SocialUserPrincipal socialUserPrincipalProviderId = new SocialUserPrincipal(Types.providerId, "providerId");
    subject.getPrincipals().add(socialUserPrincipalProviderId);
    SocialUserPrincipal socialUserPrincipalDisplayName = new SocialUserPrincipal(Types.displayName,
            "displayName");
    subject.getPrincipals().add(socialUserPrincipalDisplayName);
    SocialUserPrincipal socialUserPrincipalEmail = new SocialUserPrincipal(Types.email, "email");
    subject.getPrincipals().add(socialUserPrincipalEmail);
    SocialUserPrincipal socialUserPrincipalFirstName = new SocialUserPrincipal(Types.firstName, "firstName");
    subject.getPrincipals().add(socialUserPrincipalFirstName);
    SocialUserPrincipal socialUserPrincipalLastName = new SocialUserPrincipal(Types.lastName, "lastName");
    subject.getPrincipals().add(socialUserPrincipalLastName);
    SocialUserPrincipal socialUserPrincipalUserId = new SocialUserPrincipal(Types.userId, "userId");
    subject.getPrincipals().add(socialUserPrincipalUserId);
    SocialUserPrincipal socialUserPrincipalUS = new SocialUserPrincipal("unsupported", "unsupported");
    subject.getPrincipals().add(socialUserPrincipalUS);

    SocialUserContext suCtx = initContexts(subject);

    Assert.assertNotNull(suCtx);/*from   w  w  w .j a va2  s.c  om*/
    Assert.assertEquals(suCtx.getProviderId(), "providerId");
    Assert.assertEquals(suCtx.getDisplayName(), "displayName");
    Assert.assertEquals(suCtx.getEmail(), "email");
    Assert.assertEquals(suCtx.getFirstName(), "firstName");
    Assert.assertEquals(suCtx.getLastName(), "lastName");
    Assert.assertEquals(suCtx.getUserId(), "userId");
}

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

@Test
public void testAuthnSuccess() throws Exception {
    MockHttpServletRequest httpRequest = initHttpRequest();
    MockHttpServletResponse httpResponse = new MockHttpServletResponse();
    httpRequest.setRequestURI(subjectAuthenticator);
    servlet.service(httpRequest, httpResponse);
    Assert.assertNull(httpRequest.getAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY));
    Subject subject = (Subject) httpRequest.getAttribute(ExternalAuthentication.SUBJECT_KEY);
    Assert.assertEquals(subject.getPrincipals().iterator().next().getName(), username);
}

From source file:org.apache.qpid.server.security.access.plugins.DefaultAccessControl.java

public Result authoriseFromAddress(Operation operation, ObjectType objectType, ObjectProperties properties,
        InetAddress addressOfClient) {
    final Subject subject = SecurityManager.getThreadSubject();
    // Abstain if there is no subject/principal associated with this thread
    if (subject == null || subject.getPrincipals().size() == 0) {
        return Result.ABSTAIN;
    }//from w  ww .java2s  .c om

    if (_logger.isDebugEnabled()) {
        _logger.debug("Checking " + operation + " " + objectType + " "
                + ObjectUtils.defaultIfNull(addressOfClient, ""));
    }

    try {
        return _ruleSet.check(subject, operation, objectType, properties, addressOfClient);
    } catch (Exception e) {
        _logger.error("Unable to check " + operation + " " + objectType + " "
                + ObjectUtils.defaultIfNull(addressOfClient, ""), e);
        return Result.DENIED;
    }
}

From source file:org.apache.hadoop.gateway.identityasserter.function.UsernameFunctionProcessorTest.java

@Test
public void testResolve() throws Exception {
    final UsernameFunctionProcessor processor = new UsernameFunctionProcessor();
    assertThat(processor.resolve(null, null), nullValue());
    assertThat(processor.resolve(null, Arrays.asList("test-input")), contains("test-input"));
    Subject subject = new Subject();
    subject.getPrincipals().add(new PrimaryPrincipal("test-username"));
    subject.setReadOnly();/*from  ww w  . j av  a2s.  c om*/
    Subject.doAs(subject, new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
            assertThat(processor.resolve(null, null), contains("test-username"));
            assertThat(processor.resolve(null, Arrays.asList("test-ignored")), contains("test-username"));
            return null;
        }
    });
}

From source file:org.josso.tc50.agent.CatalinaNativeRealm.java

@Override
public Principal authenticate(String username, String credentials) {
    try {// ww  w .ja  v  a  2  s  .c  o m
        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

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

        SSOUser ssoUser = im.findUserInSession(requester, username);

        Principal principal = null;

        if (ssoUser != null) {
            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
            }
            // Return the appropriate Principal for this authenticated Subject
            principal = createPrincipal(username, subject);
        }

        return principal;
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage());
        }
        return null;
    } catch (Exception e) {
        log.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
}