Search in sources :

Example 1 with RevocableToken

use of org.cloudfoundry.identity.uaa.oauth.token.RevocableToken in project uaa by cloudfoundry.

the class TokenMvcMockTests method testPasswordGrantTokenForDefaultZone_Opaque.

@Test
void testPasswordGrantTokenForDefaultZone_Opaque() throws Exception {
    Map<String, String> parameters = new HashedMap();
    parameters.put(REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue());
    String tokenKey = "access_token";
    Map<String, Object> tokenResponse = testRevocablePasswordGrantTokenForDefaultZone(parameters);
    assertNotNull("Token must be present", tokenResponse.get(tokenKey));
    assertTrue("Token must be a string", tokenResponse.get(tokenKey) instanceof String);
    String token = (String) tokenResponse.get(tokenKey);
    assertThat("Token must be shorter than 37 characters", token.length(), lessThanOrEqualTo(36));
    RevocableToken revocableToken = webApplicationContext.getBean(RevocableTokenProvisioning.class).retrieve(token, IdentityZoneHolder.get().getId());
    assertNotNull("Token should have been stored in the DB", revocableToken);
    Jwt jwt = JwtHelper.decode(revocableToken.getValue());
    Map<String, Object> claims = JsonUtils.readValue(jwt.getClaims(), new TypeReference<Map<String, Object>>() {
    });
    assertNotNull("Revocable claim must exist", claims.get(ClaimConstants.REVOCABLE));
    assertTrue("Token revocable claim must be set to true", (Boolean) claims.get(ClaimConstants.REVOCABLE));
}
Also used : JdbcRevocableTokenProvisioning(org.cloudfoundry.identity.uaa.oauth.token.JdbcRevocableTokenProvisioning) RevocableTokenProvisioning(org.cloudfoundry.identity.uaa.oauth.token.RevocableTokenProvisioning) RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) Jwt(org.cloudfoundry.identity.uaa.oauth.jwt.Jwt) Matchers.containsString(org.hamcrest.Matchers.containsString) HashedMap(org.apache.commons.collections.map.HashedMap) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) LinkedHashMap(java.util.LinkedHashMap) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) Test(org.junit.jupiter.api.Test)

Example 2 with RevocableToken

use of org.cloudfoundry.identity.uaa.oauth.token.RevocableToken in project uaa by cloudfoundry.

the class TokenMvcMockTests method validateRevocableJwtToken.

private void validateRevocableJwtToken(Map<String, Object> tokenResponse, IdentityZone zone) {
    String tokenKey = "access_token";
    assertNotNull("Token must be present", tokenResponse.get(tokenKey));
    assertTrue("Token must be a string", tokenResponse.get(tokenKey) instanceof String);
    String token = (String) tokenResponse.get(tokenKey);
    assertThat("Token must be longer than 36 characters", token.length(), greaterThan(36));
    Jwt jwt = JwtHelper.decode(token);
    Map<String, Object> claims = JsonUtils.readValue(jwt.getClaims(), new TypeReference<Map<String, Object>>() {
    });
    assertNotNull("JTI Claim should be present", claims.get(JTI));
    String tokenId = (String) claims.get(JTI);
    IdentityZoneHolder.set(zone);
    RevocableToken revocableToken = webApplicationContext.getBean(RevocableTokenProvisioning.class).retrieve(tokenId, IdentityZoneHolder.get().getId());
    IdentityZoneHolder.clear();
    assertNotNull("Token should have been stored in the DB", revocableToken);
    jwt = JwtHelper.decode(revocableToken.getValue());
    claims = JsonUtils.readValue(jwt.getClaims(), new TypeReference<Map<String, Object>>() {
    });
    assertNotNull("Revocable claim must exist", claims.get(ClaimConstants.REVOCABLE));
    assertTrue("Token revocable claim must be set to true", (Boolean) claims.get(ClaimConstants.REVOCABLE));
    assertEquals(token, revocableToken.getValue());
}
Also used : JdbcRevocableTokenProvisioning(org.cloudfoundry.identity.uaa.oauth.token.JdbcRevocableTokenProvisioning) RevocableTokenProvisioning(org.cloudfoundry.identity.uaa.oauth.token.RevocableTokenProvisioning) Jwt(org.cloudfoundry.identity.uaa.oauth.jwt.Jwt) RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) Matchers.containsString(org.hamcrest.Matchers.containsString) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Map(java.util.Map) HashedMap(org.apache.commons.collections.map.HashedMap) LinkedHashMap(java.util.LinkedHashMap) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap)

Example 3 with RevocableToken

use of org.cloudfoundry.identity.uaa.oauth.token.RevocableToken in project uaa by cloudfoundry.

the class ListUserTokenMockMvcTests method getTokenList.

List<RevocableToken> getTokenList(String urlTemplate, String accessToken, ResultMatcher status) throws Exception {
    MvcResult result = mockMvc.perform(get(urlTemplate).header(AUTHORIZATION, "Bearer " + accessToken)).andExpect(status).andReturn();
    if (result.getResponse().getStatus() == 200) {
        String response = result.getResponse().getContentAsString();
        List<RevocableToken> tokenList = JsonUtils.readValue(response, new TypeReference<List<RevocableToken>>() {
        });
        tokenList.forEach(t -> assertNull(t.getValue()));
        return tokenList;
    } else {
        return emptyList();
    }
}
Also used : RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) MvcResult(org.springframework.test.web.servlet.MvcResult)

Example 4 with RevocableToken

use of org.cloudfoundry.identity.uaa.oauth.token.RevocableToken in project uaa by cloudfoundry.

the class UserTokenMockMvcTests method test_user_managed_token.

@Test
void test_user_managed_token() throws Exception {
    String recipientId = "recipientClient" + new RandomValueStringGenerator().generate();
    BaseClientDetails recipient = setUpClients(recipientId, "uaa.user", "uaa.user,test.scope", "password," + GRANT_TYPE_REFRESH_TOKEN, true, TEST_REDIRECT_URI, Collections.singletonList("uaa"), 50000);
    String requestorId = "requestingClient" + new RandomValueStringGenerator().generate();
    BaseClientDetails requestor = setUpClients(requestorId, "uaa.user", "uaa.user", "password," + GRANT_TYPE_USER_TOKEN, true, TEST_REDIRECT_URI, Collections.singletonList("uaa"));
    String username = "testuser" + new RandomValueStringGenerator().generate();
    String userScopes = "uaa.user,test.scope";
    setUpUser(jdbcScimUserProvisioning, jdbcScimGroupMembershipManager, jdbcScimGroupProvisioning, username, userScopes, OriginKeys.UAA, IdentityZone.getUaaZoneId());
    String requestorToken = MockMvcUtils.getUserOAuthAccessToken(mockMvc, requestorId, SECRET, username, SECRET, "uaa.user");
    String response = mockMvc.perform(post("/oauth/token").header(HttpHeaders.AUTHORIZATION, "Bearer " + requestorToken).accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).param(OAuth2Utils.GRANT_TYPE, GRANT_TYPE_USER_TOKEN).param(OAuth2Utils.CLIENT_ID, recipientId).param(OAuth2Utils.SCOPE, "test.scope").param("expires_in", "44000")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    Map<String, Object> result = JsonUtils.readValue(response, new TypeReference<Map<String, Object>>() {
    });
    String refreshToken = (String) result.get(REFRESH_TOKEN);
    assertNotNull(refreshToken);
    assertThat(refreshToken.length(), lessThanOrEqualTo(36));
    assertEquals("test.scope", result.get("scope"));
    assertNull(result.get(ACCESS_TOKEN));
    RevocableToken token = revocableTokenProvisioning.retrieve(refreshToken, identityZoneManager.getCurrentIdentityZoneId());
    assertEquals(recipientId, token.getClientId());
    response = mockMvc.perform(post("/oauth/token").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).param(OAuth2Utils.GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken).param(OAuth2Utils.CLIENT_ID, recipientId).param(CLIENT_SECRET, SECRET)).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    result = JsonUtils.readValue(response, new TypeReference<Map<String, Object>>() {
    });
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) Matchers.containsString(org.hamcrest.Matchers.containsString) RandomValueStringGenerator(org.springframework.security.oauth2.common.util.RandomValueStringGenerator) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Map(java.util.Map) Test(org.junit.jupiter.api.Test)

Example 5 with RevocableToken

use of org.cloudfoundry.identity.uaa.oauth.token.RevocableToken in project uaa by cloudfoundry.

the class UaaTokenServices method persistRevocableToken.

CompositeToken persistRevocableToken(String tokenId, CompositeToken token, CompositeExpiringOAuth2RefreshToken refreshToken, String clientId, String userId, boolean isOpaque, boolean isRevocable) {
    String scope = token.getScope().toString();
    long now = timeService.getCurrentTimeMillis();
    if (isRevocable) {
        RevocableToken revocableAccessToken = new RevocableToken().setTokenId(tokenId).setClientId(clientId).setExpiresAt(token.getExpiration().getTime()).setIssuedAt(now).setFormat(isOpaque ? OPAQUE.getStringValue() : JWT.getStringValue()).setResponseType(ACCESS_TOKEN).setZoneId(IdentityZoneHolder.get().getId()).setUserId(userId).setScope(scope).setValue(token.getValue());
        try {
            tokenProvisioning.create(revocableAccessToken, IdentityZoneHolder.get().getId());
        } catch (DuplicateKeyException updateInstead) {
            tokenProvisioning.update(tokenId, revocableAccessToken, IdentityZoneHolder.get().getId());
        }
    }
    boolean isRefreshTokenOpaque = isOpaque || OPAQUE.getStringValue().equals(getActiveTokenPolicy().getRefreshTokenFormat());
    boolean refreshTokenRevocable = isRefreshTokenOpaque || getActiveTokenPolicy().isJwtRevocable();
    boolean refreshTokenUnique = getActiveTokenPolicy().isRefreshTokenUnique();
    if (refreshToken != null && refreshTokenRevocable) {
        RevocableToken revocableRefreshToken = new RevocableToken().setTokenId(refreshToken.getJti()).setClientId(clientId).setExpiresAt(refreshToken.getExpiration().getTime()).setIssuedAt(now).setFormat(isRefreshTokenOpaque ? OPAQUE.getStringValue() : JWT.getStringValue()).setResponseType(REFRESH_TOKEN).setZoneId(IdentityZoneHolder.get().getId()).setUserId(userId).setScope(scope).setValue(refreshToken.getValue());
        try {
            if (refreshTokenUnique) {
                tokenProvisioning.deleteRefreshTokensForClientAndUserId(clientId, userId, IdentityZoneHolder.get().getId());
            }
            tokenProvisioning.create(revocableRefreshToken, IdentityZoneHolder.get().getId());
        } catch (DuplicateKeyException ignore) {
        // no need to store refresh tokens again
        }
    }
    CompositeToken result = new CompositeToken(isOpaque ? tokenId : token.getValue());
    result.setIdTokenValue(token.getIdTokenValue());
    result.setExpiration(token.getExpiration());
    result.setAdditionalInformation(token.getAdditionalInformation());
    result.setScope(token.getScope());
    result.setTokenType(token.getTokenType());
    result.setRefreshToken(buildRefreshTokenResponse(refreshToken, isRefreshTokenOpaque));
    return result;
}
Also used : RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) CompositeToken(org.cloudfoundry.identity.uaa.oauth.token.CompositeToken) DuplicateKeyException(org.springframework.dao.DuplicateKeyException)

Aggregations

RevocableToken (org.cloudfoundry.identity.uaa.oauth.token.RevocableToken)14 RevocableTokenProvisioning (org.cloudfoundry.identity.uaa.oauth.token.RevocableTokenProvisioning)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 JdbcRevocableTokenProvisioning (org.cloudfoundry.identity.uaa.oauth.token.JdbcRevocableTokenProvisioning)3 UaaUser (org.cloudfoundry.identity.uaa.user.UaaUser)3 IdentityZoneManager (org.cloudfoundry.identity.uaa.zone.beans.IdentityZoneManager)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 LinkedHashMap (java.util.LinkedHashMap)2 HashedMap (org.apache.commons.collections.map.HashedMap)2 UaaPrincipal (org.cloudfoundry.identity.uaa.authentication.UaaPrincipal)2 TokenRevocationEvent (org.cloudfoundry.identity.uaa.oauth.event.TokenRevocationEvent)2 Jwt (org.cloudfoundry.identity.uaa.oauth.jwt.Jwt)2 UaaUserDatabase (org.cloudfoundry.identity.uaa.user.UaaUserDatabase)2 TokenValidation (org.cloudfoundry.identity.uaa.util.TokenValidation)2 Test (org.junit.Test)2 Test (org.junit.jupiter.api.Test)2 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)2