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.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testAvailableRepositoriesReturnedWhenNoAuthorizedRepositoriesExist() {

    Subject subject = new Subject();

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

    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<CmsRepository> availableRepositories = repositoryService.getAvailableCmsRepositories();

    Assert.assertTrue(CollectionUtils.isNotEmpty(availableRepositories), "No available repositories for test");

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

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

    for (CmsRepository cmsRepository : availableRepositories) {
        Assert.assertTrue(authorizedRepositories.contains(cmsRepository.getId()),
                "Repository id " + cmsRepository.getId() + " was not found in authorized repositories "
                        + authorizedRepositories.toString());
    }/*from  w  ww .  j  a  v  a2s. c  o  m*/

}

From source file:org.apache.karaf.jaas.modules.ldap.LdapLoginModuleTest.java

@Test
public void testTrimmedUsernameLogin() throws Exception {
    Properties options = ldapLoginModuleOptions();
    options.put("usernames.trim", "true");
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("cheese   ");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("foodie".toCharArray());
                }/*  w  w w.j  a  va  2s.  c o m*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());

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

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof UserPrincipal) {
            assertEquals("cheese", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    // cheese is not an admin so no roles should be returned
    assertFalse(foundRole);

    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
}

From source file:org.apache.storm.security.auth.ClientAuthUtilsTest.java

@Test(expected = RuntimeException.class)
public void updateSubjectWithNullAutosThrowsTest() {
    ClientAuthUtils.updateSubject(new Subject(), null, null);
}

From source file:org.apache.storm.security.auth.ClientAuthUtilsTest.java

@Test
public void updateSubjectWithNullAutosTest() {
    AuthUtilsTestMock mock = Mockito.mock(AuthUtilsTestMock.class);
    Collection<IAutoCredentials> autos = Arrays.asList(new IAutoCredentials[] { mock });
    Subject s = new Subject();
    ClientAuthUtils.updateSubject(s, autos, null);
    Mockito.verify(mock, Mockito.times(1)).updateSubject(s, null);
}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test
public void testSuccess() throws Exception {

    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }// w ww. j  ava  2  s.c o m
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());

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

    boolean foundKrb5User = false;
    boolean foundUser = false;
    boolean foundRole = false;
    boolean foundTicket = false;

    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundKrb5User = true;
        } else if (pr instanceof UserPrincipal) {
            assertEquals("hnelson", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    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());
            foundTicket = true;
            break;
        }
    }

    assertTrue("Principals should contains kerberos user", foundKrb5User);
    assertTrue("Principals should contains ldap user", foundUser);
    assertTrue("Principals should contains ldap role", foundRole);
    assertTrue("PricatePrincipals should contains kerberos ticket", foundTicket);

    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
}

From source file:org.forgerock.openam.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * Overridden as to call different method on underlying JASPI JwtSessionModule.
 *
 * @param callbacks {@inheritDoc}/*from  www  .j a v a2  s.c o m*/
 * @param state {@inheritDoc}
 * @return {@inheritDoc}
 * @throws LoginException {@inheritDoc}
 */
@Override
public int process(Callback[] callbacks, int state) throws LoginException {
    switch (state) {
    case ISAuthConstants.LOGIN_START: {
        setUserSessionProperty(JwtSessionModule.TOKEN_IDLE_TIME_CLAIM_KEY, tokenIdleTime.toString());
        setUserSessionProperty(JwtSessionModule.MAX_TOKEN_LIFE_KEY, maxTokenLife.toString());
        setUserSessionProperty(SECURE_COOKIE_KEY, Boolean.toString(secureCookie));
        setUserSessionProperty(HTTP_ONLY_COOKIE_KEY, Boolean.toString(httpOnlyCookie));
        final Subject clientSubject = new Subject();
        MessageInfo messageInfo = prepareMessageInfo(getHttpServletRequest(), getHttpServletResponse());
        if (process(messageInfo, clientSubject, callbacks)) {
            return ISAuthConstants.LOGIN_SUCCEED;
        }
        throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "cookieNotValid", null);
    }
    default: {
        throw new AuthLoginException(AUTH_RESOURCE_BUNDLE_NAME, "incorrectState", null);
    }
    }
}

From source file:org.apache.karaf.jaas.modules.krb5.Krb5LoginModuleTest.java

@Test(expected = LoginException.class)
public void testKeytabFailure() throws Exception {

    Map<String, Object> props = new HashMap<>();
    props.put("debug", "true");
    props.put("useKeyTab", "true");
    props.put("keyTab", createKeytab());
    props.put("principal", "hnelson0@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.assertFalse(module.login());//  w w  w .j a  v a2 s . co  m

}

From source file:org.apache.storm.security.auth.AuthUtilsTest.java

@Test(expected = RuntimeException.class)
public void updateSubjectWithNullAutosThrowsTest() {
    AuthUtils.updateSubject(new Subject(), null, null);
}

From source file:com.fiveamsolutions.nci.commons.authentication.LoginModuleTest.java

@Test(expected = CredentialExpiredException.class)
public void testPasswordExpiration() throws Exception {
    String un = "user";
    String pw = "Password1";
    LoginModule module = new CommonLoginModule();
    Map<String, ?> options = new HashMap<String, Object>();
    Map<String, ?> sharedState = new HashMap<String, Object>();
    Subject subject = new Subject();
    CallbackHandler cbh = new MockCallbackHandler(un, pw.toCharArray());
    module.initialize(subject, cbh, sharedState, options);
    Long userId = createUser(un, pw);
    assertTrue(module.login());//w  w w  . j  av  a2 s  .  com
    assertTrue(!sharedState.isEmpty());

    sharedState.clear();
    updatePasswordExpirationDate(userId, null);
    assertTrue(module.login());
    assertTrue(!sharedState.isEmpty());

    sharedState.clear();
    updatePasswordExpirationDate(userId, DateUtils.addDays(new Date(), -1));
    module.login();
}

From source file:org.apache.storm.security.auth.AuthUtilsTest.java

@Test
public void updateSubjectWithNullAutosTest() {
    AuthUtilsTestMock mock = Mockito.mock(AuthUtilsTestMock.class);
    Collection<IAutoCredentials> autos = Arrays.asList(new IAutoCredentials[] { mock });
    Subject s = new Subject();
    AuthUtils.updateSubject(s, autos, null);
    Mockito.verify(mock, Mockito.times(1)).updateSubject(s, null);
}