Search in sources :

Example 31 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class CheckTokenEndpointTests method setUp.

public void setUp(boolean opaque) throws Exception {
    zone = MultitenancyFixture.identityZone("id", "subdomain");
    defaultZone = IdentityZone.getUaa();
    mockIdentityZoneManager = mock(IdentityZoneManager.class);
    when(mockIdentityZoneManager.getCurrentIdentityZoneId()).thenReturn(IdentityZone.getUaaZoneId());
    when(mockIdentityZoneManager.getCurrentIdentityZone()).thenReturn(defaultZone);
    clientDetailsService = new InMemoryMultitenantClientServices(mockIdentityZoneManager);
    TestUtils.resetIdentityZoneHolder(null);
    nowMillis = 10000L;
    timeService = mock(TimeService.class);
    when(timeService.getCurrentTimeMillis()).thenReturn(nowMillis);
    when(timeService.getCurrentDate()).thenCallRealMethod();
    userAuthorities = new ArrayList<>();
    userAuthorities.add(new SimpleGrantedAuthority("read"));
    userAuthorities.add(new SimpleGrantedAuthority("write"));
    userAuthorities.add(new SimpleGrantedAuthority("zones.myzone.admin"));
    userAuthorities.addAll(UaaAuthority.USER_AUTHORITIES);
    user = new UaaUser(userId, userName, "password", userEmail, userAuthorities, "GivenName", "FamilyName", new Date(nowMillis - 2000), new Date(nowMillis - 2000), OriginKeys.UAA, "externalId", false, IdentityZoneHolder.get().getId(), "salt", new Date(nowMillis - 2000));
    authorizationRequest = new AuthorizationRequest("client", Collections.singleton("read"));
    authorizationRequest.setResourceIds(new HashSet<>(Arrays.asList("client", "scim")));
    Map<String, String> requestParameters = new HashMap<>();
    tokenProvisioning = mock(RevocableTokenProvisioning.class);
    if (opaque) {
        tokenMap = new HashMap<>();
        when(tokenProvisioning.create(any(), anyString())).thenAnswer(invocation -> {
            RevocableToken token = (RevocableToken) invocation.getArguments()[0];
            tokenMap.put(token.getTokenId(), token);
            return token;
        });
        when(tokenProvisioning.retrieve(anyString(), anyString())).thenAnswer(invocation -> {
            String id = (String) invocation.getArguments()[0];
            return tokenMap.get(id);
        });
        requestParameters.put(TokenConstants.REQUEST_TOKEN_FORMAT, OPAQUE.getStringValue());
    }
    authorizationRequest.setRequestParameters(requestParameters);
    authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), UaaAuthenticationTestFactory.getAuthentication(userId, userName, "olds@vmware.com"));
    configureDefaultZoneKeys(Collections.singletonMap("testKey", signerKey));
    IdentityZoneHolder.set(defaultZone);
    when(zoneProvisioning.retrieve(IdentityZone.getUaaZoneId())).thenReturn(defaultZone);
    Date oneSecondAgo = new Date(nowMillis - 1000);
    Date thirtySecondsAhead = new Date(nowMillis + 30000);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("client").setScope("read").setExpiresAt(thirtySecondsAhead).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(oneSecondAgo), IdentityZoneHolder.get().getId());
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("client").setScope("write").setExpiresAt(thirtySecondsAhead).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(oneSecondAgo), IdentityZoneHolder.get().getId());
    defaultClient = new BaseClientDetails("client", "scim, cc", "read, write", "authorization_code, password", "scim.read, scim.write, cat.pet", "http://localhost:8080/uaa");
    clientDetailsStore = Collections.singletonMap("client", defaultClient);
    clientDetailsService.setClientDetailsStore(zone.getId(), clientDetailsStore);
    clientDetailsService.setClientDetailsStore(IdentityZoneHolder.get().getId(), clientDetailsStore);
    tokenEndpointBuilder = new TokenEndpointBuilder("http://localhost:8080/uaa");
    userDatabase = mock(UaaUserDatabase.class);
    KeyInfoService keyInfoService = new KeyInfoService("http://localhost:8080/uaa");
    tokenValidationService = new TokenValidationService(tokenProvisioning, tokenEndpointBuilder, userDatabase, clientDetailsService, keyInfoService);
    ApprovalService approvalService = new ApprovalService(timeService, approvalStore);
    tokenServices = new UaaTokenServices(mock(IdTokenCreator.class), tokenEndpointBuilder, clientDetailsService, tokenProvisioning, tokenValidationService, null, timeService, new TokenValidityResolver(new ClientAccessTokenValidity(clientDetailsService, mockIdentityZoneManager), Integer.MAX_VALUE, timeService), userDatabase, Sets.newHashSet(), IdentityZoneHolder.get().getConfig().getTokenPolicy(), keyInfoService, new IdTokenGranter(approvalService), approvalService);
    resetAndMockUserDatabase(userId, user);
    endpoint = new CheckTokenEndpoint(tokenServices, timeService);
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ApprovalService(org.cloudfoundry.identity.uaa.approval.ApprovalService) UaaUserDatabase(org.cloudfoundry.identity.uaa.user.UaaUserDatabase) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) RevocableToken(org.cloudfoundry.identity.uaa.oauth.token.RevocableToken) UaaUser(org.cloudfoundry.identity.uaa.user.UaaUser) Approval(org.cloudfoundry.identity.uaa.approval.Approval) IdentityZoneManager(org.cloudfoundry.identity.uaa.zone.beans.IdentityZoneManager) InMemoryMultitenantClientServices(org.cloudfoundry.identity.uaa.zone.InMemoryMultitenantClientServices) RevocableTokenProvisioning(org.cloudfoundry.identity.uaa.oauth.token.RevocableTokenProvisioning) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) TimeService(org.cloudfoundry.identity.uaa.util.TimeService) IdTokenGranter(org.cloudfoundry.identity.uaa.oauth.openid.IdTokenGranter) Date(java.util.Date) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication)

Example 32 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class DeprecatedUaaTokenServicesTests method testCreateAccessTokenRefreshGrantSomeScopesAutoApproved.

@Test
public void testCreateAccessTokenRefreshGrantSomeScopesAutoApproved() {
    BaseClientDetails clientDetails = cloneClient(tokenSupport.defaultClient);
    clientDetails.setAutoApproveScopes(tokenSupport.readScope);
    tokenSupport.clientDetailsService.setClientDetailsStore(IdentityZoneHolder.get().getId(), Collections.singletonMap(CLIENT_ID, clientDetails));
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    Calendar updatedAt = Calendar.getInstance();
    updatedAt.add(Calendar.MILLISECOND, -1000);
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.writeScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(OPENID).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED).setLastUpdatedAt(updatedAt.getTime()), IdentityZoneHolder.get().getId());
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = tokenSupport.defaultUserAuthentication;
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    this.assertCommonUserAccessTokenProperties(accessToken, CLIENT_ID);
    assertThat(accessToken, issuerUri(is(ISSUER_URI)));
    assertThat(accessToken, scope(is(tokenSupport.requestedAuthScopes)));
    assertThat(accessToken, validFor(is(60 * 60 * 12)));
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    this.assertCommonUserRefreshTokenProperties(refreshToken);
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI)));
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30)));
    this.assertCommonEventProperties(accessToken, tokenSupport.userId, buildJsonString(tokenSupport.requestedAuthScopes));
    AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN);
    refreshAuthorizationRequest.setRequestParameters(refreshAzParameters);
    OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"));
    assertEquals(refreshedAccessToken.getRefreshToken().getValue(), accessToken.getRefreshToken().getValue());
    this.assertCommonUserAccessTokenProperties(refreshedAccessToken, CLIENT_ID);
    assertThat(refreshedAccessToken, issuerUri(is(ISSUER_URI)));
    assertThat(refreshedAccessToken, validFor(is(60 * 60 * 12)));
    assertThat(accessToken.getRefreshToken(), is(not(nullValue())));
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) CompositeExpiringOAuth2RefreshToken(org.cloudfoundry.identity.uaa.oauth.refresh.CompositeExpiringOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) IsEmptyString.isEmptyString(org.hamcrest.text.IsEmptyString.isEmptyString) Approval(org.cloudfoundry.identity.uaa.approval.Approval)

Example 33 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class DeprecatedUaaTokenServicesTests method testRefreshTokenAfterApprovalsRevoked.

@Test(expected = InvalidTokenException.class)
public void testRefreshTokenAfterApprovalsRevoked() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = tokenSupport.defaultUserAuthentication;
    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    tokenSupport.approvalStore.addApproval(new Approval().setUserId(tokenSupport.userId).setClientId(CLIENT_ID).setScope(tokenSupport.readScope.get(0)).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId());
    for (Approval approval : tokenSupport.approvalStore.getApprovals(tokenSupport.userId, CLIENT_ID, IdentityZoneHolder.get().getId())) {
        tokenSupport.approvalStore.revokeApproval(approval, IdentityZoneHolder.get().getId());
    }
    AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, tokenSupport.requestedAuthScopes);
    refreshAuthorizationRequest.setResourceIds(new HashSet<>(tokenSupport.resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN);
    refreshAuthorizationRequest.setRequestParameters(refreshAzParameters);
    tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"));
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) IsEmptyString.isEmptyString(org.hamcrest.text.IsEmptyString.isEmptyString) Approval(org.cloudfoundry.identity.uaa.approval.Approval)

Example 34 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class UserManagedAuthzApprovalHandlerTests method requestedScopesMatchApprovalButSomeDenied.

@Test
void requestedScopesMatchApprovalButSomeDenied() {
    AuthorizationRequest request = new AuthorizationRequest("foo", new HashSet<>(Arrays.asList("openid", "cloud_controller.read", "cloud_controller.write")));
    request.setApproved(false);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("foo").setScope("openid").setExpiresAt(nextWeek).setStatus(APPROVED), currentIdentityZoneId);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("foo").setScope("cloud_controller.read").setExpiresAt(nextWeek).setStatus(APPROVED), currentIdentityZoneId);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("foo").setScope("cloud_controller.write").setExpiresAt(nextWeek).setStatus(DENIED), currentIdentityZoneId);
    // The request is approved because the user has acted on all requested
    // scopes
    assertTrue(handler.isApproved(request, mockAuthentication));
    assertEquals(new HashSet<>(Arrays.asList("openid", "cloud_controller.read")), request.getScope());
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) Approval(org.cloudfoundry.identity.uaa.approval.Approval) Test(org.junit.jupiter.api.Test)

Example 35 with Approval

use of org.cloudfoundry.identity.uaa.approval.Approval in project uaa by cloudfoundry.

the class UserManagedAuthzApprovalHandlerTests method requestedScopesDontMatchApprovalsAtAll.

@Test
void requestedScopesDontMatchApprovalsAtAll() {
    AuthorizationRequest request = new AuthorizationRequest("foo", new HashSet<>(Collections.singletonList("openid")));
    request.setApproved(false);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("foo").setScope("cloud_controller.read").setExpiresAt(nextWeek).setStatus(APPROVED), currentIdentityZoneId);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId("foo").setScope("cloud_controller.write").setExpiresAt(nextWeek).setStatus(DENIED), currentIdentityZoneId);
    // The request is not approved because the user has not yet approved the
    // scopes requested
    assertFalse(handler.isApproved(request, mockAuthentication));
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) Approval(org.cloudfoundry.identity.uaa.approval.Approval) Test(org.junit.jupiter.api.Test)

Aggregations

Approval (org.cloudfoundry.identity.uaa.approval.Approval)80 Test (org.junit.jupiter.api.Test)34 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)29 Date (java.util.Date)26 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)21 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)19 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)18 Authentication (org.springframework.security.core.Authentication)17 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)17 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)16 Test (org.junit.Test)16 ApprovalStore (org.cloudfoundry.identity.uaa.approval.ApprovalStore)7 MockHttpServletRequestBuilder (org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder)6 ClientDetailsModification (org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification)5 ScimUser (org.cloudfoundry.identity.uaa.scim.ScimUser)5 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)5 ArrayList (java.util.ArrayList)4 ClientDetailsHelper.arrayFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.arrayFromString)4 ClientDetailsHelper.clientArrayFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientArrayFromString)4 ClientDetailsHelper.clientFromString (org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientFromString)4