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.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

/**
 * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(SaslServer, byte[])
 *///from  ww w . ja va  2s. c  o  m
public AuthenticationResult authenticate(SaslServer server, byte[] response) {
    try {
        // Process response from the client
        byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);

        if (server.isComplete()) {
            final Subject subject = new Subject();
            subject.getPrincipals().add(new UsernamePrincipal(server.getAuthorizationID()));
            return new AuthenticationResult(subject);
        } else {
            return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
        }
    } catch (SaslException e) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}

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

@Test(expected = LoginException.class)
public void testUsernameFailure() 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("hnelson0");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }// w  ww. ja v  a  2  s.  c om
            }
        }
    };
    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.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

private void setupContextForInternalIdentityStore(String identityStoreRepositoryId) {

    //Since we are using the internal identity store, we must setup the security context
    //for the user who will be used to connect to the repository which represents the
    //identity store. This user is the SYSTEM user by default and thus we perform
    //an internal login without the need of the SYSTEM's password
    Subject subject = new Subject();

    //System identity
    subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

    //Grant SYSTEM all roles
    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
    }/*from   w  w w  .j a v a 2 s .  co  m*/
    subject.getPrincipals().add(rolesPrincipal);

    //Login using the Subject, the provided roles and SYSTEM's permanent key and get the authentication token
    authenticationTokenForSYSTEMofInternalIdentityStore = repositoryDao.login(identityStoreRepositoryId,
            subject, RepositoryRegistry.INSTANCE.getPermanentKeyForUser(identityStoreRepositoryId,
                    IdentityPrincipal.SYSTEM));

}

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

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

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

    //Test for Nimbus itself as a user
    Subject nimbus = getNimbusSubject();
    assertStoreHasExactly(store);
    metadata = new SettableBlobMeta(BlobStoreAclHandler.DEFAULT);
    try (AtomicOutputStream out = store.createBlob("test", metadata, nimbus)) {
        assertStoreHasExactly(store, "test");
        out.write(1);
    }
    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);
    try (AtomicOutputStream out = store.createBlob("test", metadata, who)) {
        out.write(1);
    }
    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);
    try (AtomicOutputStream out = store.createBlob("test", metadata, who)) {
        out.write(2);
    }
    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");
    try (AtomicOutputStream out = store.updateBlob("test", who)) {
        out.write(3);
    }
    assertStoreHasExactly(store, "test");
    readAssertEqualsWithAuth(store, who, "test", 3);

    LOG.info("Updating test again");
    try (AtomicOutputStream 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");
    try (AtomicOutputStream out = store.createBlob("test-empty-subject-WE", metadata, who)) {
        out.write(2);
    }
    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");

    try (AtomicOutputStream out = store.createBlob("test-empty-subject-DEF", metadata, who)) {
        out.write(2);
    }
    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 LocalFsBlobStore) {
        ((LocalFsBlobStore) store).fullCleanup(1);
    } else {
        fail("Error the blobstore is of unknowntype");
    }
}

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

@Test(expected = LoginException.class)
public void testLoginUsernameFailure() 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("hnelson0");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }//from  w w  w .j  a v a2  s.  co 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.infoscoop.web.SessionManagerFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    if (log.isDebugEnabled()) {
        log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI());
    }/*  w ww  .  j a  v a  2 s.c  om*/

    if (request instanceof javax.servlet.http.HttpServletRequest) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String uid = null;
        if (SessionCreateConfig.doLogin()) {
            uid = getUidFromSession(httpReq);

            if (uid != null) {
                addUidToSession(uid, request);
            }

            if (redirectPaths.contains(httpReq.getServletPath())) {
                httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath()));
            }
            if (uid == null && !isExcludePath(httpReq.getServletPath())) {
                if (httpRequest.getHeader("MSDPortal-Ajax") != null) {
                    if (log.isInfoEnabled())
                        log.info("session timeout has occured. logoff automatically.");
                    httpResponse.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SESSION_TIMEOUT);
                    httpResponse.sendError(500);
                    return;
                }
            }
        } else {
            uid = getUidFromHeader(httpReq);
            if (uid == null)
                uid = getUidFromSession(httpReq);
            if (uid != null) {
                addUidToSession(uid, request);
            }
        }

        if (uid == null) {
            Cookie[] cookies = httpReq.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("portal-credential")) {
                        int keepPeriod = 7;
                        try {
                            keepPeriod = Integer.parseInt(PropertiesDAO.newInstance()
                                    .findProperty("loginStateKeepPeriod").getValue());
                        } catch (Exception ex) {
                            log.warn("", ex);
                        }

                        if (keepPeriod <= 0) {
                            Cookie credentialCookie = new Cookie("portal-credential", "");
                            credentialCookie.setMaxAge(0);
                            credentialCookie.setPath("/");
                            httpResponse.addCookie(credentialCookie);

                            log.info("clear auto login credential [" + credentialCookie.getValue() + "]");
                        } else {
                            try {
                                uid = tryAutoLogin(cookie);
                                httpReq.getSession().setAttribute("Uid", uid);

                                log.info("auto login success.");
                            } catch (Exception ex) {
                                log.info("auto login failed.", ex);
                            }
                        }
                    }
                }
            }
        }

        if (uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) {
            String requestUri = httpReq.getRequestURI();
            String loginUrl = requestUri.lastIndexOf("/manager/") > 0
                    ? requestUri.substring(0, requestUri.lastIndexOf("/")) + "/../login.jsp"
                    : "login.jsp";

            httpResponse.sendRedirect(loginUrl);
            return;
        }

        if (log.isInfoEnabled())
            log.info("### Access from user " + uid + " to " + httpReq.getRequestURL());

        // fix #42
        //         setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid);
        HttpSession session = httpRequest.getSession();

        Subject loginUser = (Subject) session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME);

        if (loginUser == null || (isChangeLoginUser(uid, loginUser)
                && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession))) {
            if (!SessionCreateConfig.getInstance().hasUidHeader() && uid != null) {
                AuthenticationService service = AuthenticationService.getInstance();
                try {
                    if (service != null)
                        loginUser = service.getSubject(uid);
                } catch (Exception e) {
                    log.error("", e);
                }
            }

            if (loginUser == null || isChangeLoginUser(uid, loginUser)) {
                loginUser = new Subject();
                loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid));
            }

            setLoginUserName(httpRequest, loginUser);

            for (Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()) {
                String headerName = (String) entry.getKey();
                String roleType = (String) entry.getValue();
                Enumeration headerValues = httpRequest.getHeaders(headerName);
                while (headerValues.hasMoreElements()) {
                    String headerValue = (String) headerValues.nextElement();
                    try {
                        Set principals = loginUser.getPrincipals();
                        principals.add(new ISPrincipal(roleType, headerValue));
                        //                     loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) );
                        if (log.isInfoEnabled())
                            log.info("Set principal to login subject: " + roleType + "=" + headerValue);
                    } catch (IllegalArgumentException e) {
                        log.error("", e);
                    } catch (SecurityException e) {
                        log.error("", e);
                    }
                }

            }
            session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser);
        }
        SecurityController.registerContextSubject(loginUser);
        if (httpRequest.getHeader("X-IS-TIMEZONE") != null) {
            int timeZoneOffset = 0;
            try {
                timeZoneOffset = Integer.parseInt(httpRequest.getHeader("X-IS-TIMEZONE"));
            } catch (NumberFormatException e) {
                if (log.isDebugEnabled())
                    log.debug(httpRequest.getHeader("X-IS-TIMEZONE"), e);
            } finally {
                UserContext.instance().getUserInfo().setClientTimezoneOffset(timeZoneOffset);
            }
        }
    }
    chain.doFilter(request, response);

    if (log.isDebugEnabled()) {
        log.debug("Exit SessionManagerFilterform " + httpReq.getRequestURI());
    }

}

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

@Test
public void testEmptyPassword() throws Exception {
    Properties options = ldapLoginModuleOptions();
    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("imnothere");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("".toCharArray());
                }//from   www.  j  a  v a  2s.  c  om
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    try {
        module.login();
        fail("Should have failed");
    } catch (LoginException e) {
        assertTrue(e.getMessage().equals("Empty passwords not allowed"));
    }
}

From source file:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Finish the authentication process successfully.
 * //from w w  w.j ava2  s  . c o  m
 * <p>Sets the attribute {@link ExternalAuthentication#SUBJECT_KEY}.</p>
 * 
 * @param key the conversation key
 * @param httpRequest the HTTP request
 * @param httpResponse the HTTP response
 * @param kerberosPrincipal the Kerberos principal to return
 * 
 * @throws IOException 
 * @throws ExternalAuthenticationException 
 */
private void finishWithSuccess(@Nonnull @NotEmpty final String key,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse,
        @Nonnull final KerberosPrincipal kerberosPrincipal)
        throws ExternalAuthenticationException, IOException {

    // Store the user as a username and as a real KerberosPrincipal object.
    final Subject subject = new Subject();
    subject.getPrincipals().add(new UsernamePrincipal(kerberosPrincipal.getName()));
    subject.getPrincipals().add(kerberosPrincipal);

    // Finish the external authentication task and return to the flow.
    httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);
    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

/**
 * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(String, String)
 *///  www. j a  v  a  2 s . co  m
public AuthenticationResult authenticate(final String username, final String password) {
    try {
        if (_principalDatabase.verifyPassword(username, password.toCharArray())) {
            final Subject subject = new Subject();
            subject.getPrincipals().add(new UsernamePrincipal(username));
            return new AuthenticationResult(subject);
        } else {
            return new AuthenticationResult(AuthenticationStatus.CONTINUE);
        }
    } catch (AccountNotFoundException e) {
        return new AuthenticationResult(AuthenticationStatus.CONTINUE);
    }
}

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

@Test(expected = LoginException.class)
public void testPasswordFailure() 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("secret0".toCharArray());
                }/*w  ww.  ja va  2s  . co  m*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

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