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.helios.ember.auth.SSHLoginService.java

/**
 * /* w w w .  j av  a  2s  . c  o m*/
 * <p><b><code>username</code></b> can be:<ol>
 *    <li><code>username</code></li>
 *    <li><code>username@hostname</code></li>
 *    <li><code>username@hostname:port</code></li>
 * </ol></p>
 * <p>However, a <code>":&lt;port&gt;"</code> in the username will be parsed out (in the browser ?) and prepended to the credentials as <code>"&lt;port&gt;:"</code> 
 * so technically #3 will never been seen, so:<ul>
 *    <li>If we see #1, strip and ignore (or error out) on a leading <code>":&lt;port&gt;"</code> in the credentials</li>
 *  <li>If we see #2, check the credentials a leading <code>":&lt;port&gt;"</code> and strip it out.</li>
 * </ul></p>
 * {@inheritDoc}
 * @see org.eclipse.jetty.security.LoginService#login(java.lang.String, java.lang.Object)
 */
@SuppressWarnings("unchecked")
@Override
public UserIdentity login(String username, Object credentials) {
    SessionLogin sessionLogin = SessionLogin.newSessionLogin(pkRepo.getJSch(), username, credentials);
    if (sessionLogin == null)
        return null;
    if (!sessionLogin.login(5000)) { // should be a param
        return null;
    }
    // ===== user authenticated, set up subject and principal
    Subject subject = new Subject();
    subject.getPrincipals().add(new RolePrincipal("foo"));

    if (subject.getPrivateCredentials().isEmpty()) {
        subject.getPrivateCredentials().add(new HashMap<String, String>(
                Collections.singletonMap(sessionLogin.getSessionKey(), sessionLogin.getPassword())));
        subject.getPublicCredentials().add(new HashMap<String, SessionLogin>(
                Collections.singletonMap(sessionLogin.getSessionKey(), sessionLogin)));
    } else {
        ((HashMap<String, String>) subject.getPrivateCredentials().iterator().next())
                .put(sessionLogin.getSessionKey(), sessionLogin.getPassword());
        ((HashMap<String, SessionLogin>) subject.getPublicCredentials().iterator().next())
                .put(sessionLogin.getSessionKey(), sessionLogin);
    }
    subject.getPrivateCredentials().add(sessionLogin.getPassword());
    subject.getPublicCredentials().add(sessionLogin.getSession());
    return new DefaultUserIdentity(subject, sessionLogin, new String[] { "foo" });
}

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

@Test
public void populateSubjectTest() {
    AuthUtilsTestMock autoCred = Mockito.mock(AuthUtilsTestMock.class);
    Subject subject = new Subject();
    Map<String, String> cred = new HashMap<String, String>();
    Collection<IAutoCredentials> autos = Arrays.asList(new IAutoCredentials[] { autoCred });
    AuthUtils.populateSubject(subject, autos, cred);
    Mockito.verify(autoCred, Mockito.times(1)).populateSubject(subject, cred);
}

From source file:org.atricore.idbus.kernel.main.federation.AccountLinkLifecycleImpl.java

public Subject resolve(AccountLink accountLink) throws AccountLinkageException {

    Subject resolvedSubject = new Subject();

    if (identityStore == null) {

        String userId = accountLink.getLocalAccountNameIdentifier() != null
                ? accountLink.getLocalAccountNameIdentifier()
                : accountLink.getId();//from   w ww  . ja v a  2  s.c  om

        // TODO : What type of username are we using here?
        resolvedSubject.getPrincipals().add(new SubjectNameID(userId, null));

        if (logger.isDebugEnabled())
            logger.debug("No local identity store, returning local subject as " + resolvedSubject);

        return resolvedSubject;
    }

    UserKey uid = new SimpleUserKey(accountLink.getLocalAccountNameIdentifier());

    try {
        logger.debug("Resolving account link : " + accountLink.getLocalAccountNameIdentifier());

        if (identityStore.userExists(uid)) {

            BaseUser user = identityStore.loadUser(uid);

            // map it to josso2 subject data model
            resolvedSubject.getPrincipals().add(
                    // TODO : What type of username are we using here?
                    new SubjectNameID(user.getName(), null));

            SSONameValuePair[] ssoUserProperties = user.getProperties();

            for (SSONameValuePair ssoUserProperty : ssoUserProperties) {
                resolvedSubject.getPrincipals()
                        .add(new SubjectAttribute(ssoUserProperty.getName(), ssoUserProperty.getValue()));
            }

            BaseRole[] roles = identityStore.findRolesByUserKey(uid);

            for (BaseRole role : roles) {
                resolvedSubject.getPrincipals().add(new SubjectRole(role.getName()));
            }
        } else {
            logger.warn("User [" + uid + "] does not exists in Identity Store (" + identityStore
                    + ") ! Cannot resolve account link " + accountLink.getId());
        }

    } catch (SSOIdentityException e) {
        throw new AccountLinkageException(
                "Error resolving account link [" + accountLink.getId() + "] " + e.getMessage(), e);
    }

    return resolvedSubject;
}

From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java

@Test
public void testInvalidPermanentKey() {
    Subject subject = new Subject();

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

    String permanentKey = "invalidPermanentKey";

    try {//  ww w  .  j av a 2 s.co  m
        repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);
    } catch (Exception e) {

        Assert.assertTrue((e instanceof CmsException), "Unexpected exception during invalid login");

        Assert.assertEquals(e.getMessage(), "Invalid permanent key " + permanentKey + " for user " + identity
                + " in repository " + TestConstants.TEST_REPOSITORY_ID);
    }

    identity = TestConstants.TEST_USER_NAME;
    subject.getPrincipals().remove(identityPrincipal);
    identityPrincipal = new IdentityPrincipal(identity);
    subject.getPrincipals().add(identityPrincipal);

    try {
        repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, permanentKey);
    } catch (Exception e) {

        Assert.assertTrue((e instanceof CmsException), "Unexpected exception during invalid login");

        Assert.assertEquals(e.getMessage(), "Invalid permanent key " + permanentKey + " for user " + identity
                + " in repository " + TestConstants.TEST_REPOSITORY_ID);
    }

}

From source file:org.betaconceptframework.astroboa.console.security.IdentityStoreRunAsSystem.java

private Subject createSubjectForSystemUserAndItsRoles(String cmsRepositoryId) {

    Subject subject = new Subject();

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

    //Load default roles for SYSTEM USER
    //Must return at list one group named "Roles" in order to be 
    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, cmsRepositoryId)));
    }/*from w w  w .  j  a v  a 2s.c o  m*/

    subject.getPrincipals().add(rolesPrincipal);

    return subject;
}

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

@Test
public void populateSubjectTest() {
    AuthUtilsTestMock autoCred = Mockito.mock(AuthUtilsTestMock.class);
    Subject subject = new Subject();
    Map<String, String> cred = new HashMap<String, String>();
    Collection<IAutoCredentials> autos = Arrays.asList(new IAutoCredentials[] { autoCred });
    ClientAuthUtils.populateSubject(subject, autos, cred);
    Mockito.verify(autoCred, Mockito.times(1)).populateSubject(subject, cred);
}

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   www . j  a v  a  2  s .  co  m*/
    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.waveprotocol.box.server.robots.agent.passwd.PasswordRobot.java

/**
 * Verifies user credentials.//from w  w w. j  a  va 2  s  . c o m
 * 
 * @param oldPassword the password to verify.
 * @param participantId the participantId of the user.
 * @throws LoginException if the user provided incorrect password.
 */
private void verifyCredentials(String password, ParticipantId participantId) throws LoginException {
    MultiMap<String> parameters = new MultiMap<String>();
    parameters.putAllValues(ImmutableMap.of("password", password, "address", participantId.getAddress()));
    CallbackHandler callbackHandler = new HttpRequestBasedCallbackHandler(parameters);
    LoginContext context = new LoginContext("Wave", new Subject(), callbackHandler, configuration);
    // If authentication fails, login() will throw a LoginException.
    context.login();
}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.SPNameIDManagementProducer.java

@Override
protected void doProcess(CamelMediationExchange exchange) throws Exception {
    //      try{/*from   w  ww . ja va  2  s  . c  om*/
    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();
    ManageNameIDRequestType manageNameID = (ManageNameIDRequestType) in.getMessage().getContent();

    StatusType status = new StatusType();
    StatusCodeType statusCode = new StatusCodeType();
    statusCode.setValue(StatusCode.TOP_SUCCESS.getValue());
    status.setStatusCode(statusCode);

    boolean validated = true;
    StringBuffer secondaryErrorCode = new StringBuffer();

    try {
        manageNameID = validateManageNameID(manageNameID, secondaryErrorCode);
    } catch (SSORequestException e1) {
        logger.error("Error validating ManageNameIDRequest", e1);
        validated = false;
    }

    if (validated) {
        if (manageNameID.getTerminate() != null) {
            SubjectNameID subjectNameID = null;
            if (manageNameID.getNameID() != null) {
                subjectNameID = new SubjectNameID(manageNameID.getNameID().getValue(),
                        manageNameID.getNameID().getFormat());
                subjectNameID.setLocalName(manageNameID.getNameID().getSPProvidedID());
            } else {
                NameIDType decryptedNameID = null;
                SamlR2Encrypter encrypter = ((SSOSPMediator) channel.getIdentityMediator()).getEncrypter();
                try {
                    decryptedNameID = encrypter.decryptNameID(manageNameID.getEncryptedID());
                } catch (SamlR2EncrypterException e) {
                    //TODO should we throw RuntimeException?
                    throw new SSOException("NameID cannot be decrypted.", e);
                }
                subjectNameID = new SubjectNameID(decryptedNameID.getValue(), decryptedNameID.getFormat());
                subjectNameID.setLocalName(decryptedNameID.getSPProvidedID());
            }
            Subject idpSubject = new Subject();
            idpSubject.getPrincipals().add(subjectNameID);

            // check if there is an existing session for the user
            FederationChannel fChannel = (FederationChannel) channel;

            // if not, check if channel is federation-capable
            if (fChannel.getAccountLinkLifecycle() == null) {

                // cannot map subject to local account, terminate
                logger.error("No Account Lifecycle configured for Channel [" + fChannel.getName() + "] "
                        + " ManageNameID [" + manageNameID.getID() + "]");
                throw new SSOException("No Account Lifecycle configured for Channel [" + fChannel.getName()
                        + "] " + " ManageNameID [" + manageNameID.getID() + "]");
            }

            AccountLinkLifecycle accountLinkLifecycle = fChannel.getAccountLinkLifecycle();
            AccountLink accountLink = accountLinkLifecycle.findByIDPAccount(idpSubject);
            if (accountLink == null) {
                logger.error("No Account Link available for Principal [" + subjectNameID.getName() + "]");
                throw new SSOException(
                        "No Account Link available for Principal [" + subjectNameID.getName() + "]");
            }
            accountLinkLifecycle.dispose(accountLink);
        }
    }

    // ---------------------------------------------------
    // Send ManageNameIDResponse
    // ---------------------------------------------------

    CircleOfTrustMemberDescriptor idp = this.resolveIdp();
    logger.debug("Using IDP " + idp.getAlias());

    // Select endpoint, must be a ManageNameIDService endpoint
    EndpointType idpSsoEndpoint = resolveIdpMNIDEndpoint(idp);
    EndpointDescriptor destination = new EndpointDescriptorImpl("IDPMNIEndpoint", "ManageNameIDService",
            idpSsoEndpoint.getBinding(), idpSsoEndpoint.getLocation(), idpSsoEndpoint.getResponseLocation());

    StatusResponseType mnidResponse = buildMNIDResponse(exchange, idp, idpSsoEndpoint, validated,
            secondaryErrorCode.toString());

    CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();
    out.setMessage(new MediationMessageImpl(mnidResponse.getID(), mnidResponse, "ManageNameIDResponse", null,
            destination, in.getMessage().getState()));

    exchange.setOut(out);
}

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

@Override
public Subject getSubject(HttpServletRequest httpRequest) throws SocialUserAuthenticationException {
    log.trace("Entering");
    try {//from ww  w  .  j  ava 2s .  co m
        TokenRequest request = getTokenRequest(httpRequest);
        if (request == null) {
            log.debug("User is not authenticated yet");
            log.trace("Leaving");
            return null;
        }
        HTTPRequest req = request.toHTTPRequest();
        req.setQuery(request.toHTTPRequest().getQuery() + getClientCredentialsTrail());
        TokenResponse tokenResponse = TokenResponse.parse(req.send());
        if (!tokenResponse.indicatesSuccess()) {
            TokenErrorResponse errorResponse = (TokenErrorResponse) tokenResponse;
            String error = "error in token fetch";
            if (errorResponse != null && errorResponse.getErrorObject() != null
                    && errorResponse.getErrorObject().getCode() != null) {
                error = errorResponse.getErrorObject().getCode();
                String errorDescription = errorResponse.getErrorObject().getDescription();
                if (errorDescription != null && !errorDescription.isEmpty()) {
                    error += " : " + errorDescription;
                }
            }
            log.error("error:" + error);
            log.trace("Leaving");
            throw new SocialUserAuthenticationException(error, SocialUserErrorIds.EXCEPTION);
        }
        AccessTokenResponse tokenSuccessResponse = (AccessTokenResponse) tokenResponse;
        // Get the access token, the server may also return a refresh token
        AccessToken accessToken = tokenSuccessResponse.getAccessToken();
        // try reading stuff from accesstoken
        Subject subject = new Subject();
        parsePrincipalsFromClaims(subject, accessToken.toJSONObject());
        if (getUserinfoEndpoint() != null && !getUserinfoEndpoint().toString().isEmpty()) {
            // The protected resource insists on having access token as
            // query parameter
            // access token should be in headers
            URL resourceURL = new URL(
                    getUserinfoEndpoint().toString() + "&access_token=" + accessToken.getValue());
            URLConnection conn = resourceURL.openConnection();
            String userinfo = IOUtils.toString(conn.getInputStream());
            conn.getInputStream().close();
            try {
                parsePrincipalsFromClaims(subject, JSONObjectUtils.parseJSONObject(userinfo));
            } catch (java.text.ParseException e) {
                log.error("error parsing userinfo endpoint");
                log.trace("Leaving");
                throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
            }
        }
        addDefaultPrincipals(subject);
        return subject;

    } catch (SerializeException | IOException | URISyntaxException | ParseException e) {
        log.error("Something bad happened " + e.getMessage());
        log.error(e.getMessage());
        log.trace("Leaving");
        throw new SocialUserAuthenticationException(e.getMessage(), SocialUserErrorIds.EXCEPTION);
    }

}