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.forgerock.tinker.authentication.modules.persistentcookie.PersistentCookieAuthModule.java

/**
 * Overridden as to call different method on underlying JASPI JwtSessionModule.
 *
 * @param callbacks {@inheritDoc}/*w ww . j  a v a 2 s . co  m*/
 * @param state {@inheritDoc}
 * @return {@inheritDoc}
 * @throws LoginException {@inheritDoc}
 */
@Override
public int process(Callback[] callbacks, int state) throws LoginException {

    DEBUG.message("TINKER: PersistentCookieAuthenticationModule.process() - 1.");

    switch (state) {
    case ISAuthConstants.LOGIN_START: {
        setUserSessionProperty(JwtSessionModule.TOKEN_IDLE_TIME_CLAIM_KEY, tokenIdleTime.toString());
        setUserSessionProperty(JwtSessionModule.MAX_TOKEN_LIFE_KEY, maxTokenLife.toString());
        setUserSessionProperty(ENFORCE_CLIENT_IP_SETTING_KEY, Boolean.toString(enforceClientIP));
        setUserSessionProperty(SECURE_COOKIE_KEY, Boolean.toString(secureCookie));
        setUserSessionProperty(HTTP_ONLY_COOKIE_KEY, Boolean.toString(httpOnlyCookie));
        if (cookieName != null) {
            setUserSessionProperty(COOKIE_NAME_KEY, cookieName);
        }
        String cookieDomainsString = "";
        for (String cookieDomain : cookieDomains) {
            cookieDomainsString += cookieDomain + ",";
        }
        setUserSessionProperty(COOKIE_DOMAINS_KEY, cookieDomainsString);
        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 testLoginPasswordFailure() throws Exception {
    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("secret0".toCharArray());
                }//from  ww w  . j  ava  2s.  c o  m
            }
        }
    };
    Subject subject = new Subject();

    Krb5LoginModule module = new Krb5LoginModule();
    module.initialize(subject, cb, null, new HashMap<>());

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

    Assert.assertFalse(module.login());

}

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

/**
 * @return a security handler/*from www . jav a 2  s .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.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * It does the Kerberos authentication when it has to be done through 
 * username and password. It looks in the default Kerberos domain defined 
 * in the Kerberos config file (krb5.ini or krb5.conf) if there is a valid 
 * user with those credentials. If so, it gets his/her Kerberos ticket.
 * //from ww  w  .  j a  v a  2  s.co m
 * @param userCred username and password credentials
 *
 * @return the method result in HTTP error format
 */
public int authUsernamePassword(Credential userCred) {

    int result = HttpServletResponse.SC_UNAUTHORIZED;

    Krb5LoginModule login = null;
    userSubject = new Subject();

    logger.debug("authUsernamePassword: using username and password");

    try {

        //Create config objects and pass the credentials      
        Map state = new HashMap();
        UsernamePasswordCredentials usrpwdCred = new UsernamePasswordCredentials(userCred.getUsername(),
                userCred.getPassword());
        state.put("javax.security.auth.login.name", usrpwdCred.getUserName());
        state.put("javax.security.auth.login.password", usrpwdCred.getPassword().toCharArray());
        state.put("java.security.krb5.conf", krbini);

        if (logger.isDebugEnabled()) {
            logger.debug("Username: " + usrpwdCred.getUserName());
        }

        Map option = new HashMap();
        String isDebug = "false";
        if (logger.isDebugEnabled()) {
            isDebug = "true";
        }
        option.put("debug", isDebug);
        option.put("tryFirstPass", "true");
        option.put("useTicketCache", "false");
        option.put("doNotPrompt", "false");
        option.put("storePass", "false");
        option.put("forwardable", "true");

        login = new Krb5LoginModule();
        login.initialize(userSubject, new NegotiateCallbackHandler(), state, option);

        if (login.login()) {
            login.commit();
            logger.debug("Login commit");
            if (id == null) {
                username = usrpwdCred.getUserName();
                id = username;
            }
            logger.debug("username is ... " + id);
            result = HttpServletResponse.SC_OK;
        }
    } catch (LoginException e) {
        logger.error("LoginException while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_UNAUTHORIZED;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Exception while creating id: " + e.getMessage(), e);
        result = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return result;

}

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

@Test
public void testRoleMappingSimple() throws Exception {
    Properties options = ldapLoginModuleOptions();
    options.put(LDAPOptions.ROLE_MAPPING, "admin=karaf");
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        @Override/*w w w . j av  a2  s . c om*/
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("admin123".toCharArray());
                }
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

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

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

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal principal : subject.getPrincipals()) {
        if (principal instanceof UserPrincipal) {
            assertEquals("admin", principal.getName());
            foundUser = true;
        } else if (principal instanceof RolePrincipal) {
            assertEquals("karaf", principal.getName());
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);

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

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

@Test(expected = LoginException.class)
public void testUserNotFound() 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("test");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("test".toCharArray());
                }//  w  w w .j  ava 2  s  . c o m
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertFalse(module.login());
}

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

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

    Properties options = ldapLoginModuleOptions();
    options.remove(GSSAPILdapLoginModule.REALM_PROPERTY);
    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("hnelson0");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }// w ww. j a v a 2s . c  o  m
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login()); // should throw LoginException
}

From source file:org.apache.storm.hdfs.blobstore.BlobStoreTest.java

public void testWithAuthentication(BlobStore store) throws Exception {
    //Test for Nimbus Admin
    Subject admin = getSubject("admin");
    assertStoreHasExactly(store);//from   w  w w .ja  v a2 s  .c  om
    SettableBlobMeta metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    AtomicOutputStream out = store.createBlob("test", metadata, admin);
    assertStoreHasExactly(store, "test");
    out.write(1);
    out.close();
    store.deleteBlob("test", admin);

    //Test for Supervisor Admin
    Subject supervisor = getSubject("supervisor");
    assertStoreHasExactly(store);
    metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    out = store.createBlob("test", metadata, supervisor);
    assertStoreHasExactly(store, "test");
    out.write(1);
    out.close();
    store.deleteBlob("test", supervisor);

    //Test for Nimbus itself as a user
    Subject nimbus = getNimbusSubject();
    assertStoreHasExactly(store);
    metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    out = store.createBlob("test", metadata, nimbus);
    assertStoreHasExactly(store, "test");
    out.write(1);
    out.close();
    store.deleteBlob("test", nimbus);

    // Test with a dummy test_subject for cases where subject !=null (security turned on)
    Subject who = getSubject("test_subject");
    assertStoreHasExactly(store);

    // Tests for case when subject != null (security turned on) and
    // acls for the blob are set to WORLD_EVERYTHING
    metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
    out = store.createBlob("test", metadata, who);
    out.write(1);
    out.close();
    assertStoreHasExactly(store, "test");
    // Testing whether acls are set to WORLD_EVERYTHING
    assertTrue("ACL does not contain WORLD_EVERYTHING",
            metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
    readAssertEqualsWithAuth(store, who, "test", 1);

    LOG.info("Deleting test");
    store.deleteBlob("test", who);
    assertStoreHasExactly(store);

    // Tests for case when subject != null (security turned on) and
    // acls are not set for the blob (DEFAULT)
    LOG.info("Creating test again");
    metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    out = store.createBlob("test", metadata, who);
    out.write(2);
    out.close();
    assertStoreHasExactly(store, "test");
    // Testing whether acls are set to WORLD_EVERYTHING. Here the acl should not contain WORLD_EVERYTHING because
    // the subject is neither null nor empty. The ACL should however contain USER_EVERYTHING as user needs to have
    // complete access to the blob
    assertTrue("ACL does not contain WORLD_EVERYTHING",
            !metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
    readAssertEqualsWithAuth(store, who, "test", 2);

    LOG.info("Updating test");
    out = store.updateBlob("test", who);
    out.write(3);
    out.close();
    assertStoreHasExactly(store, "test");
    readAssertEqualsWithAuth(store, who, "test", 3);

    LOG.info("Updating test again");
    out = store.updateBlob("test", who);
    out.write(4);
    out.flush();
    LOG.info("SLEEPING");
    Thread.sleep(2);
    assertStoreHasExactly(store, "test");
    readAssertEqualsWithAuth(store, who, "test", 3);

    //Test for subject with no principals and acls set to WORLD_EVERYTHING
    who = new Subject();
    metadata = new SettableBlobMeta(BlobStoreAclHandler.WORLD_EVERYTHING);
    LOG.info("Creating test");
    out = store.createBlob("test-empty-subject-WE", metadata, who);
    out.write(2);
    out.close();
    assertStoreHasExactly(store, "test-empty-subject-WE", "test");
    // Testing whether acls are set to WORLD_EVERYTHING
    assertTrue("ACL does not contain WORLD_EVERYTHING",
            metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
    readAssertEqualsWithAuth(store, who, "test-empty-subject-WE", 2);

    //Test for subject with no principals and acls set to DEFAULT
    who = new Subject();
    metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    LOG.info("Creating other");
    out = store.createBlob("test-empty-subject-DEF", metadata, who);
    out.write(2);
    out.close();
    assertStoreHasExactly(store, "test-empty-subject-DEF", "test", "test-empty-subject-WE");
    // Testing whether acls are set to WORLD_EVERYTHING
    assertTrue("ACL does not contain WORLD_EVERYTHING",
            metadata.toString().contains("AccessControl(type:OTHER, access:7)"));
    readAssertEqualsWithAuth(store, who, "test-empty-subject-DEF", 2);

    if (store instanceof HdfsBlobStore) {
        ((HdfsBlobStore) store).fullCleanup(1);
    } else {
        fail("Error the blobstore is of unknowntype");
    }
    try {
        out.close();
    } catch (IOException e) {
        //This is likely to happen when we try to commit something that
        // was cleaned up.  This is expected and acceptable.
    }
}

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

@Test
public void testRoleMappingAdvanced() throws Exception {
    Properties options = ldapLoginModuleOptions();
    options.put(LDAPOptions.ROLE_MAPPING, "admin=karaf,test;admin=another");
    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("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("admin123".toCharArray());
                }/*from  w  w  w. j a v a 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(4, subject.getPrincipals().size());

    final List<String> roles = new ArrayList<String>(Arrays.asList("karaf", "test", "another"));

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal principal : subject.getPrincipals()) {
        if (principal instanceof UserPrincipal) {
            assertEquals("admin", principal.getName());
            foundUser = true;
        } else if (principal instanceof RolePrincipal) {
            assertTrue(roles.remove(principal.getName()));
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);
    assertTrue(roles.isEmpty());

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

From source file:org.globus.workspace.client_common.TempBaseClient.java

public void setOptions(Stub stub) throws Exception {

    if (this.descriptorFile != null) {
        stub._setProperty(Constants.CLIENT_DESCRIPTOR_FILE, this.descriptorFile);
        return;//from   ww  w.j a  v  a  2  s. c  om
    }

    if (this.protection != null) {
        // this means if both transport security and message security
        // are enabled both will get the same protection
        if (this.endpoint.getAddress().getScheme().equals("https")) {
            stub._setProperty(GSIConstants.GSI_TRANSPORT, this.protection);
        }
        if (this.mechanism != null) {
            stub._setProperty(this.mechanism, this.protection);
        }
    }

    if (this.convActor != null) {
        stub._setProperty("gssActor", this.convActor);
    }

    if (this.delegation != null) {
        stub._setProperty(GSIConstants.GSI_MODE, this.delegation);
    }

    if (this.authorization != null) {
        stub._setProperty(Constants.AUTHORIZATION, this.authorization);
    }

    if (this.anonymous != null) {
        stub._setProperty(Constants.GSI_ANONYMOUS, this.anonymous);
    }

    if (this.msgActor != null) {
        stub._setProperty("x509Actor", this.msgActor);
    }

    if ((Constants.GSI_SEC_MSG.equals(this.mechanism)) && (Constants.ENCRYPTION.equals(this.protection))) {
        Subject subject = new Subject();
        X509Certificate serverCert = CertUtil.loadCertificate(publicKeyFilename);
        EncryptionCredentials encryptionCreds = new EncryptionCredentials(new X509Certificate[] { serverCert });
        subject.getPublicCredentials().add(encryptionCreds);
        stub._setProperty(Constants.PEER_SUBJECT, subject);
    }

    if (this.contextLifetime != null) {
        stub._setProperty(Constants.CONTEXT_LIFETIME, this.contextLifetime);
    }

    final GSSCredential usercred = NimbusCredential.getGSSCredential();
    if (usercred != null) {
        stub._setProperty(GSIConstants.GSI_CREDENTIALS, usercred);
    }
}