Example usage for org.springframework.security.oauth2.provider AuthorizationRequest setResourceIds

List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setResourceIds

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider AuthorizationRequest setResourceIds.

Prototype

public void setResourceIds(Set<String> resourceIds) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    Map<String, Object> claims = getClaimsForToken(accessToken);

    // Check token expiry
    Integer expiration = (Integer) claims.get(EXP);
    if (expiration != null && new Date(expiration * 1000l).before(new Date())) {
        throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at "
                + new Date(expiration * 1000l));
    }//from  ww w  .j  a v  a 2s . com

    // Check client ID is valid
    validateClient((String) claims.get(CLIENT_ID));
    validateClient((String) claims.get(CID));

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);

    AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID),
            scopes);

    ArrayList<String> rids = (ArrayList<String>) claims.get(AUD);
    //TODO - Fix null resource IDs for a client_credentials request to /oauth/token
    Set<String> resourceIds = Collections
            .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids));
    authorizationRequest.setResourceIds(resourceIds);

    authorizationRequest.setApproved(true);

    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
            StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities));
    if (claims.containsKey("authorities")) {
        Object authoritiesFromClaims = claims.get("authorities");
        if (authoritiesFromClaims instanceof String) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims);
        }
        if (authoritiesFromClaims instanceof Collection) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims));
        }
    }

    Authentication userAuthentication = null;
    // Is this a user token?
    if (claims.containsKey(EMAIL)) {
        UaaUser user = new UaaUser((String) claims.get(USER_ID), (String) claims.get(USER_NAME), null,
                (String) claims.get(EMAIL), UaaAuthority.USER_AUTHORITIES, null, null, null, null, null, null,
                false);

        UaaPrincipal principal = new UaaPrincipal(user);
        userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null);
    } else {
        authorizationRequest.setAuthorities(authorities);
    }

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);
    authentication.setAuthenticated(true);
    return authentication;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
    if (StringUtils.isEmpty(accessToken)) {
        throw new InvalidTokenException(
                "Invalid access token value, must be at least 30 characters:" + accessToken);
    }//ww w . j a v  a  2s. c  o  m

    TokenValidation tokenValidation = validateToken(accessToken);
    Map<String, Object> claims = tokenValidation.getClaims();
    accessToken = tokenValidation.getJwt().getEncoded();

    // Check token expiry
    Integer expiration = (Integer) claims.get(EXP);
    if (expiration != null && new Date(expiration * 1000l).before(new Date())) {
        throw new InvalidTokenException("Invalid access token (expired): " + accessToken + " expired at "
                + new Date(expiration * 1000l));
    }

    @SuppressWarnings("unchecked")
    ArrayList<String> scopes = (ArrayList<String>) claims.get(SCOPE);

    AuthorizationRequest authorizationRequest = new AuthorizationRequest((String) claims.get(CLIENT_ID),
            scopes);

    ArrayList<String> rids = (ArrayList<String>) claims.get(AUD);
    //TODO - Fix null resource IDs for a client_credentials request to /oauth/token
    Set<String> resourceIds = Collections
            .unmodifiableSet(rids == null ? new HashSet<String>() : new HashSet<>(rids));
    authorizationRequest.setResourceIds(resourceIds);

    authorizationRequest.setApproved(true);

    Collection<? extends GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
            StringUtils.collectionToCommaDelimitedString(defaultUserAuthorities));
    if (claims.containsKey("authorities")) {
        Object authoritiesFromClaims = claims.get("authorities");
        if (authoritiesFromClaims instanceof String) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) authoritiesFromClaims);
        }
        if (authoritiesFromClaims instanceof Collection) {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authoritiesFromClaims));
        }
    }

    Authentication userAuthentication = null;
    // Is this a user token - minimum info is user_id
    if (claims.containsKey(USER_ID)) {
        UaaUser user = userDatabase.retrieveUserById((String) claims.get(USER_ID));
        UaaPrincipal principal = new UaaPrincipal(user);
        userAuthentication = new UaaAuthentication(principal, UaaAuthority.USER_AUTHORITIES, null);
    } else {
        authorizationRequest.setAuthorities(authorities);
    }

    OAuth2Authentication authentication = new UaaOauth2Authentication(accessToken,
            IdentityZoneHolder.get().getId(), authorizationRequest.createOAuth2Request(), userAuthentication);
    authentication.setAuthenticated(true);
    return authentication;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void is_opaque_token_required() {
    defaultClient.setAutoApproveScopes(singleton("true"));
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token")));
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, TokenConstants.GRANT_TYPE_USER_TOKEN);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*  w ww .  j av  a2s.  c  o  m*/
    assertTrue(tokenServices.opaqueTokenRequired(authentication));
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateAccessTokenForAClient() {

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);//from   w w w  .ja v  a  2  s .c  om

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    assertCommonClientAccessTokenProperties(accessToken);
    assertThat(accessToken, validFor(is(accessTokenValidity)));
    assertThat(accessToken, issuerUri(is(ISSUER_URI)));
    assertThat(accessToken, zoneId(is(IdentityZoneHolder.get().getId())));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
    validateExternalAttributes(accessToken);

    assertCommonEventProperties(accessToken, CLIENT_ID, expectedJson);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

protected OAuth2AccessToken performPasswordGrant(String tokenFormat) {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, PASSWORD);
    azParameters.put(REQUEST_TOKEN_FORMAT, tokenFormat);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);//from   w ww .  j  a v a 2s. c  o m
    return tokenServices.createAccessToken(authentication);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateOpaqueAccessTokenForAClient() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE);
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);/*from  ww  w  .  j  a  v a 2 s  .c  o  m*/

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    assertTrue("Token is not a composite token", accessToken instanceof CompositeAccessToken);
    assertThat("Token value should be equal to or lesser than 36 characters", accessToken.getValue().length(),
            lessThanOrEqualTo(36));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateAccessTokenForAClientInAnotherIdentityZone() {
    String subdomain = "test-zone-subdomain";
    IdentityZone identityZone = getIdentityZone(subdomain);
    identityZone.setConfig(JsonUtils.readValue(
            "{\"tokenPolicy\":{\"accessTokenValidity\":3600,\"refreshTokenValidity\":7200}}",
            IdentityZoneConfiguration.class));
    IdentityZoneHolder.set(identityZone);
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, clientScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            null);//from w  w w  . j a v  a2  s . co  m

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    this.assertCommonClientAccessTokenProperties(accessToken);
    assertThat(accessToken, validFor(is(3600)));
    assertThat(accessToken, issuerUri(is("http://" + subdomain + ".localhost:8080/uaa/oauth/token")));
    assertThat(accessToken.getRefreshToken(), is(nullValue()));
    validateExternalAttributes(accessToken);

    Assert.assertEquals(1, publisher.getEventCount());

    this.assertCommonEventProperties(accessToken, CLIENT_ID, expectedJson);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateAccessTokenAuthcodeGrant() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);//w w w .j  av a 2  s  .  co  m
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    validateAccessAndRefreshToken(accessToken);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateAccessTokenAuthcodeGrantSwitchedPrimaryKey() {
    String originalPrimaryKeyId = tokenPolicy.getActiveKeyId();
    try {/*  www  .  j a  v  a 2 s. c  om*/
        tokenPolicy.setActiveKeyId("otherKey");

        AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
        authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
        Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
        azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
        authorizationRequest.setRequestParameters(azParameters);
        Authentication userAuthentication = defaultUserAuthentication;

        OAuth2Authentication authentication = new OAuth2Authentication(
                authorizationRequest.createOAuth2Request(), userAuthentication);
        OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

        validateAccessAndRefreshToken(accessToken);
    } finally {
        tokenPolicy.setActiveKeyId(originalPrimaryKeyId);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testCreateAccessTokenPasswordGrant() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, PASSWORD);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*from  w w w.ja  va2  s . c  o m*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    validateAccessAndRefreshToken(accessToken);
    tokenServices.loadAuthentication(accessToken.getValue());

    //ensure that we can load without user_name claim
    tokenServices.setExcludedClaims(new HashSet(
            Arrays.asList(ClaimConstants.AUTHORITIES, ClaimConstants.USER_NAME, ClaimConstants.EMAIL)));
    accessToken = tokenServices.createAccessToken(authentication);
    assertNotNull(tokenServices.loadAuthentication(accessToken.getValue()).getUserAuthentication());

}