Example usage for org.apache.shiro.subject PrincipalCollection asList

List of usage examples for org.apache.shiro.subject PrincipalCollection asList

Introduction

In this page you can find the example usage for org.apache.shiro.subject PrincipalCollection asList.

Prototype

List asList();

Source Link

Document

Returns a single Subject's principals retrieved from all configured Realms as a List, or an empty List if there are not any principals.

Usage

From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java

License:Open Source License

@Override
public String login(Credential credential) throws ServiceException {
    String login = credential.getUsername();
    char[] password = credential.getPassword();
    boolean rememberMe = credential.isRememberMe();
    try {//  w  w w.jav a 2  s . c  o m
        if (log.isTraceEnabled()) {
            log.trace(String.format("login - %s", credential));
        }
        UsernamePasswordToken token = new UsernamePasswordToken(login, password, rememberMe);
        AuthenticationInfo info = securityManager.authenticate(token);
        if (log.isTraceEnabled()) {
            if (info instanceof SimpleAuthenticationInfo) {
                PrincipalCollection principals = ((SimpleAuthenticationInfo) info).getPrincipals();
                for (Object principal : principals.asList()) {
                    log.trace("Principal: " + principal);
                }
            }
        }
        token.clear();
        // Create subject for the current principal
        Subject subject = new Subject.Builder().principals(info.getPrincipals()).buildSubject();
        // log.trace("subject.getPrincipal(): " + subject.getPrincipal());
        // Create session
        org.apache.shiro.session.Session session = subject.getSession(true);
        if (session == null) {
            throw new ServiceException(String.format("Unable to create session for ", login));
        }
        session.setAttribute(ES_DMS_LOGIN_ATTRIBUTE, login);
        session.setAttribute(ES_DMS_ID_ATTRIBUTE, ((User) subject.getPrincipal()).getId());
        ThreadContext.bind(subject);
        // if (log.isTraceEnabled()) {
        // Subject currentUser = SecurityUtils.getSubject();
        // log.trace("currentUser.getPrincipal(): " +
        // currentUser.getPrincipal());
        // }
        return session.getId().toString();
    } catch (AuthenticationException aEx) {
        String message = String.format("Authentication failed for %s", login);
        log.error(message, aEx);
        throw new ServiceException(message);
    }
}

From source file:com.tensorwrench.shiro.realm.MongoUserPasswordRealm.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from www  .  j  av a 2s.  co  m
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

    DBCursor cursor = collection.find(new BasicDBObject("_id", new BasicDBObject("$in", principals.asList())));

    for (DBObject p : cursor) {
        Object rolesObj = p.get("roles");
        if (rolesObj != null && rolesObj instanceof List<?>) {
            for (Object r : (List<Object>) rolesObj) {
                info.addRole(r.toString());
            }
        }

        Object permissionsObj = p.get("permissions");
        if (permissionsObj != null && permissionsObj instanceof List<?>) {
            for (Object r : (List<Object>) permissionsObj) {
                info.addStringPermission(r.toString());
            }
        }
    }

    return info;
}

From source file:ddf.catalog.source.opensearch.impl.OpenSearchParserImplTest.java

License:Open Source License

private Subject getMockSubject(String principalName) {
    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    Principal principal = mock(Principal.class);
    when(securityAssertion.getPrincipal()).thenReturn(principal);
    when(principal.getName()).thenReturn(principalName);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(subject.getPrincipals()).thenReturn(principalCollection);
    return subject;
}

From source file:graphene.security.tomcat.preaa.PreAASecurityRealm.java

License:Apache License

@Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {

    logger.debug("doGetAuthorizationInfo " + principals.asList());
    // return null;
    final Set<String> roleNames = CollectionUtils.asSet((String[]) null);
    final SimpleAccount simpleAccount = new SimpleAccount(getUsername(principals), "password", getName(),
            roleNames, null);/* w  w  w.  j  a  va 2  s  .c om*/
    return simpleAccount;
}

From source file:org.codice.ddf.cxf.SecureCxfClientFactoryTest.java

License:Open Source License

private Subject setupMockSubject() throws Exception {
    Subject mockSubject = mock(Subject.class);
    PrincipalCollection mockPrincipals = mock(PrincipalCollection.class);
    SecurityAssertion mockSecurityAssertion = mock(SecurityAssertion.class);
    SecurityToken mockToken = mock(SecurityToken.class);

    when(mockSubject.getPrincipals()).thenReturn(mockPrincipals);
    when(mockPrincipals.asList()).thenReturn(Arrays.asList(mockSecurityAssertion));
    when(mockSecurityAssertion.getToken()).thenReturn(mockToken);
    when(mockToken.getToken()).thenReturn(getAssertionElement());

    return mockSubject;
}

From source file:org.codice.ddf.security.guest.realm.GuestRealmTest.java

License:Open Source License

@Test
public void testDoGetAuthenticationInfo() {
    BaseAuthenticationToken baseAuthenticationToken = new MockBaseAuthenticationToken("principal",
            "credentials", "0.0.0.0");
    baseAuthenticationToken.setAllowGuest(true);

    AuthenticationInfo authenticationInfo = guestRealm.doGetAuthenticationInfo(baseAuthenticationToken);

    assertEquals(baseAuthenticationToken.getCredentials(), authenticationInfo.getCredentials());

    PrincipalCollection principals = authenticationInfo.getPrincipals();

    assertEquals(2, principals.asList().size());

    Iterator iterator = principals.iterator();

    assertEquals("Guest@0.0.0.0", iterator.next());

    Object next = iterator.next();

    assertTrue(next instanceof SecurityAssertion);

    SecurityAssertion securityAssertion = (SecurityAssertion) next;

    assertEquals(2, securityAssertion.getAttributeStatements().get(0).getAttributes().size());

    boolean claim1 = false;
    boolean claim2 = false;
    boolean claim3 = false;
    boolean claim4 = false;
    for (Attribute attribute : securityAssertion.getAttributeStatements().get(0).getAttributes()) {
        if (attribute.getName().equals("claim1")) {
            claim1 = true;/*from   w w w. ja  v  a  2s .  c om*/
            assertEquals("value1", attribute.getValues().get(0));
        }
        if (attribute.getName().equals("claim2")) {
            claim2 = true;
            assertTrue(attribute.getValues().stream().anyMatch(v -> v.equals("value2")));
            assertTrue(attribute.getValues().stream().anyMatch(v -> v.equals("value3")));
        }
        if (attribute.getName().equals(":")) {
            claim3 = true;
        }
        if (attribute.getName().equals("bad")) {
            claim4 = true;
        }
    }
    assertTrue(claim1);
    assertTrue(claim2);
    assertFalse(claim3);
    assertFalse(claim4);

    AuthenticationInfo newAuthenticationInfo = guestRealm.doGetAuthenticationInfo(baseAuthenticationToken);

    assertNotSame(authenticationInfo, newAuthenticationInfo);
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

License:Open Source License

@Before
public void setup() throws IOException, SecurityServiceException, ParserConfigurationException, SAXException,
        URISyntaxException {/* w  ww.  j  a  va2s . com*/
    System.setProperty("org.codice.ddf.system.hostname", "localhost");
    System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
    File jksFile = temporaryFolder.newFile("serverKeystore.jks");
    FileOutputStream jksOutStream = new FileOutputStream(jksFile);
    InputStream jksStream = IdpEndpointTest.class.getResourceAsStream("/serverKeystore.jks");
    IOUtils.copy(jksStream, jksOutStream);
    IOUtils.closeQuietly(jksStream);
    IOUtils.closeQuietly(jksOutStream);

    File signatureFile = temporaryFolder.newFile("signature.properties");
    FileOutputStream signatureOutStream = new FileOutputStream(signatureFile);
    InputStream signatureStream = IdpEndpointTest.class.getResourceAsStream("/signature.properties");
    IOUtils.copy(signatureStream, signatureOutStream);
    IOUtils.closeQuietly(signatureStream);
    IOUtils.closeQuietly(signatureOutStream);

    File encryptionFile = temporaryFolder.newFile("encryption.properties");
    FileOutputStream encryptionOutStream = new FileOutputStream(encryptionFile);
    InputStream encryptionStream = IdpEndpointTest.class.getResourceAsStream("/encryption.properties");
    IOUtils.copy(encryptionStream, encryptionOutStream);
    IOUtils.closeQuietly(encryptionStream);
    IOUtils.closeQuietly(encryptionOutStream);

    EncryptionService encryptionService = mock(EncryptionService.class);

    when(encryptionService.decrypt(anyString())).thenReturn("changeit");
    when(encryptionService.encrypt(anyString())).thenReturn("changeit");

    SecurityManager securityManager = mock(SecurityManager.class);
    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(principalCollection.getPrimaryPrincipal()).thenReturn("testuser");
    when(securityAssertion.getToken()).thenReturn(securityToken);
    when(securityToken.getToken()).thenReturn(readDocument("/saml.xml").getDocumentElement());
    when(securityManager.getSubject(anyObject())).thenReturn(subject);

    System.setProperty("javax.net.ssl.keyStore", jksFile.getAbsolutePath());

    System.setProperty(SecurityConstants.TRUSTSTORE_TYPE, "JKS");
    System.setProperty(SecurityConstants.TRUSTSTORE_PATH,
            getClass().getResource("/serverTruststore.jks").toURI().getPath());
    System.setProperty(SecurityConstants.TRUSTSTORE_PASSWORD, "changeit");

    idpEndpoint = new IdpEndpoint(signatureFile.getAbsolutePath(), encryptionFile.getAbsolutePath(),
            encryptionService);
    idpEndpoint.setStrictSignature(true);
    idpEndpoint.init();
    idpEndpoint.setSpMetadata(Collections.singletonList(spMetadata));
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setLogoutStates(new RelayStates<>());
    STSAuthenticationTokenFactory stsAuthenticationTokenFactory = new STSAuthenticationTokenFactory();
    stsAuthenticationTokenFactory.init();
    idpEndpoint.setTokenFactory(stsAuthenticationTokenFactory);
    OcspService ocspService = mock(OcspService.class);
    idpEndpoint.setOcspService(ocspService);
    idpEndpoint.cookieCache.cacheSamlAssertion("1", readDocument("/saml.xml").getDocumentElement());
    idpEndpoint.setExpirationTime(30);

    relayState = "ef95c04b-6c05-4d12-b65f-dd32fed8811e";
    requestCertificateAttributeName = "javax.servlet.request.X509Certificate";
    requestURL = new StringBuffer("https://www.example.com");
    samlConditionDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    signature = authNRequestGetSignature;
    signatureAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
    System.setProperty("org.codice.ddf.system.rootContext", "/services");
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

License:Open Source License

@Test
public void testPassiveLoginPkiUnsupportedPost() throws Exception {
    String samlRequest = authNRequestPassivePkiPost;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    SecurityManager securityManager = mock(SecurityManager.class);

    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getToken()).thenReturn(securityToken);
    // this mock element is what will cause the signature error
    when(securityToken.getToken()).thenReturn(mock(Element.class));
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    // dummy cert
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request);
    String responseStr = XmlSearch.evaluate("/html/body/form/input[@name='SAMLResponse']/@value",
            response.getEntity().toString());
    responseStr = new String(Base64.getDecoder().decode(responseStr));

    // the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:RequestUnsupported"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

License:Open Source License

@Test
public void testPassiveLoginPkiUnsupported() throws Exception {
    String samlRequest = authNRequestPassivePkiGet;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    SecurityManager securityManager = mock(SecurityManager.class);
    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getToken()).thenReturn(securityToken);
    // this mock element is what will cause the signature error
    when(securityToken.getToken()).thenReturn(mock(Element.class));
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    // dummy cert
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);//from  w  w w .j  a  v a 2s  . c o  m
    String responseStr = XmlSearch.evaluate("/html/body/form/input[@name='SAMLResponse']/@value",
            response.getEntity().toString());
    responseStr = RestSecurity.base64Decode(responseStr);

    // the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:RequestUnsupported"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

License:Open Source License

@Test
public void testPassiveLoginPkiUnsupportedBinding() throws Exception {
    String samlRequest = authNRequestPassivePkiGetUnsupportedBinding;
    HttpServletRequest request = mock(HttpServletRequest.class);
    X509Certificate x509Certificate = mock(X509Certificate.class);

    Subject subject = mock(Subject.class);
    PrincipalCollection principalCollection = mock(PrincipalCollection.class);
    SecurityAssertion securityAssertion = mock(SecurityAssertion.class);
    SecurityToken securityToken = mock(SecurityToken.class);
    SecurityManager securityManager = mock(SecurityManager.class);
    when(subject.getPrincipals()).thenReturn(principalCollection);
    when(principalCollection.asList()).thenReturn(Collections.singletonList(securityAssertion));
    when(securityAssertion.getToken()).thenReturn(securityToken);
    // this mock element is what will cause the signature error
    when(securityToken.getToken()).thenReturn(mock(Element.class));
    when(securityManager.getSubject(anyObject())).thenReturn(subject);
    idpEndpoint.setSecurityManager(securityManager);
    idpEndpoint.setStrictSignature(false);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    // dummy cert
    when((X509Certificate[]) request.getAttribute(requestCertificateAttributeName))
            .thenReturn(new X509Certificate[] { x509Certificate });
    when(x509Certificate.getEncoded()).thenReturn(new byte[48]);

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);/*from w w  w.  j a va 2s  .c o  m*/
    String responseStr = XmlSearch.evaluate("/html/body/form/input[@name='SAMLResponse']/@value",
            response.getEntity().toString());
    responseStr = RestSecurity.base64Decode(responseStr);

    // the only cookie that should exist is the "1" cookie so "2" should send us to the login webapp
    assertThat(responseStr, containsString("status:UnsupportedBinding"));
}