Search in sources :

Example 31 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.

the class ClientAdminEndpointsIntegrationTests method testClientTxModifyApprovalsDeleted.

@Test
public void testClientTxModifyApprovalsDeleted() throws Exception {
    // create client
    ClientDetailsModification client = createClient("client_credentials", "password");
    assertNotNull(getClient(client.getClientId()));
    // issue a user token for this client
    OAuth2AccessToken userToken = getUserAccessToken(client.getClientId(), "secret", testAccounts.getUserName(), testAccounts.getPassword(), "oauth.approvals");
    // make sure we don't have any approvals
    Approval[] approvals = getApprovals(userToken.getValue(), client.getClientId());
    Assert.assertEquals(0, approvals.length);
    // create three approvals
    addApprovals(userToken.getValue(), client.getClientId());
    approvals = getApprovals(userToken.getValue(), client.getClientId());
    Assert.assertEquals(3, approvals.length);
    // delete the client
    client.setAction(ClientDetailsModification.DELETE);
    ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/oauth/clients/tx/modify"), HttpMethod.POST, new HttpEntity<BaseClientDetails[]>(new BaseClientDetails[] { client }, getAuthenticatedHeaders(getClientCredentialsAccessToken("clients.admin"))), Void.class);
    assertEquals(HttpStatus.OK, result.getStatusCode());
    // create a client that can read another clients approvals
    String deletedClientId = client.getClientId();
    client = createApprovalsClient("password");
    userToken = getUserAccessToken(client.getClientId(), "secret", testAccounts.getUserName(), testAccounts.getPassword(), "oauth.approvals");
    // make sure we don't have any approvals
    approvals = getApprovals(userToken.getValue(), deletedClientId);
    Assert.assertEquals(0, approvals.length);
    assertNull(getClient(deletedClientId));
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Approval(org.cloudfoundry.identity.uaa.approval.Approval) ClientDetailsModification(org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification) Test(org.junit.Test)

Example 32 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.

the class UaaUserApprovalHandler method isApproved.

/**
 * Allows automatic approval for a white list of clients in the implicit
 * grant case.
 *
 * @param authorizationRequest The authorization request.
 * @param userAuthentication   the current user authentication
 * @return Whether the specified request has been approved by the current
 * user.
 */
@Override
public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    if (!userAuthentication.isAuthenticated()) {
        return false;
    }
    if (authorizationRequest.isApproved()) {
        return true;
    }
    final ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId(), identityZoneManager.getCurrentIdentityZoneId());
    final Collection<String> requestedScopes = authorizationRequest.getScope();
    return isAutoApprove(client, requestedScopes);
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails)

Example 33 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.

the class UaaAuthorizationEndpoint method approveOrDeny.

@RequestMapping(value = "/oauth/authorize", method = RequestMethod.POST, params = OAuth2Utils.USER_OAUTH_APPROVAL)
public View approveOrDeny(@RequestParam Map<String, String> approvalParameters, Map<String, ?> model, SessionStatus sessionStatus, Principal principal) {
    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();
        throw new InsufficientAuthenticationException("User must be authenticated with Spring Security before authorizing an access token.");
    }
    AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get(AUTHORIZATION_REQUEST);
    if (authorizationRequest == null) {
        sessionStatus.setComplete();
        throw new InvalidRequestException("Cannot approve uninitialized authorization request.");
    }
    // Check to ensure the Authorization Request was not modified during the user approval step
    @SuppressWarnings("unchecked") Map<String, Object> originalAuthorizationRequest = (Map<String, Object>) model.get(ORIGINAL_AUTHORIZATION_REQUEST);
    if (isAuthorizationRequestModified(authorizationRequest, originalAuthorizationRequest)) {
        logger.warn("The requested scopes are invalid");
        throw new InvalidRequestException("Changes were detected from the original authorization request.");
    }
    for (String approvalParameter : approvalParameters.keySet()) {
        if (approvalParameter.startsWith(SCOPE_PREFIX)) {
            String scope = approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length());
            Set<String> originalScopes = (Set<String>) originalAuthorizationRequest.get("scope");
            if (!originalScopes.contains(scope)) {
                sessionStatus.setComplete();
                logger.warn("The requested scopes are invalid");
                return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new InvalidScopeException("The requested scopes are invalid. Please use valid scope names in the request."), false), false, true, false);
            }
        }
    }
    try {
        Set<String> responseTypes = authorizationRequest.getResponseTypes();
        String grantType = deriveGrantTypeFromResponseType(responseTypes);
        authorizationRequest.setApprovalParameters(approvalParameters);
        authorizationRequest = userApprovalHandler.updateAfterApproval(authorizationRequest, (Authentication) principal);
        boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
        authorizationRequest.setApproved(approved);
        if (authorizationRequest.getRedirectUri() == null) {
            sessionStatus.setComplete();
            throw new InvalidRequestException("Cannot approve request when no redirect URI is provided.");
        }
        if (!authorizationRequest.isApproved()) {
            return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, new UserDeniedAuthorizationException("User denied access"), responseTypes.contains("token")), false, true, false);
        }
        if (responseTypes.contains("token") || responseTypes.contains("id_token")) {
            return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType).getView();
        }
        return getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal);
    } finally {
        sessionStatus.setComplete();
    }
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) Set(java.util.Set) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) UserDeniedAuthorizationException(org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) RedirectView(org.springframework.web.servlet.view.RedirectView) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) Map(java.util.Map) HashMap(java.util.HashMap) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 34 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.

the class UaaAuthorizationEndpoint method getImplicitGrantOrHybridResponse.

// We can grant a token and return it with implicit approval.
private ModelAndView getImplicitGrantOrHybridResponse(AuthorizationRequest authorizationRequest, Authentication authentication, String grantType) {
    OAuth2AccessToken accessToken;
    try {
        TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, GRANT_TYPE_IMPLICIT);
        Map<String, String> requestParameters = new HashMap<>(authorizationRequest.getRequestParameters());
        requestParameters.put(GRANT_TYPE, grantType);
        authorizationRequest.setRequestParameters(requestParameters);
        OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest);
        accessToken = getAccessTokenForImplicitGrantOrHybrid(tokenRequest, storedOAuth2Request, grantType);
        if (accessToken == null) {
            throw new UnsupportedResponseTypeException("Unsupported response type: token or id_token");
        }
        return new ModelAndView(new RedirectView(buildRedirectURI(authorizationRequest, accessToken, authentication), false, true, false));
    } catch (OAuth2Exception e) {
        return new ModelAndView(new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false));
    }
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) HashMap(java.util.HashMap) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ImplicitTokenRequest(org.springframework.security.oauth2.provider.implicit.ImplicitTokenRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView) UnsupportedResponseTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 35 with Approval

use of org.springframework.security.oauth2.provider.approval.Approval in project uaa by cloudfoundry.

the class ClientAdminEndpointsMockMvcTests method testModifyApprovalsAreDeleted.

@Test
void testModifyApprovalsAreDeleted() throws Exception {
    ClientDetails details = createClient(adminToken, new RandomValueStringGenerator().generate(), SECRET, Collections.singleton("password"));
    ((ClientDetailsModification) details).setAction(ClientDetailsModification.DELETE);
    String userToken = testClient.getUserOAuthAccessToken(details.getClientId(), "secret", testUser.getUserName(), testPassword, "oauth.approvals");
    Approval[] approvals = getApprovals(details.getClientId());
    assertEquals(0, approvals.length);
    addApprovals(userToken, details.getClientId());
    approvals = getApprovals(details.getClientId());
    assertEquals(3, approvals.length);
    MockHttpServletRequestBuilder deleteClientsPost = post("/oauth/clients/tx/modify").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(new ClientDetails[] { details }));
    ResultActions result = mockMvc.perform(deleteClientsPost);
    result.andExpect(status().isOk());
    ClientDetailsModification[] deleted = (ClientDetailsModification[]) arrayFromString(result.andReturn().getResponse().getContentAsString(), ClientDetailsModification[].class);
    assertTrue(deleted[0].isApprovalsDeleted());
    verify(mockApplicationEventPublisher, times(2)).publishEvent(abstractUaaEventCaptor.capture());
    ClientDetails approvalsClient = createApprovalsLoginClient(adminToken);
    String loginToken = testClient.getUserOAuthAccessToken(approvalsClient.getClientId(), "secret", testUser.getUserName(), testPassword, "oauth.approvals");
    approvals = getApprovals(details.getClientId());
    assertEquals(0, approvals.length);
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) RandomValueStringGenerator(org.springframework.security.oauth2.common.util.RandomValueStringGenerator) ClientDetailsHelper.clientArrayFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientArrayFromString) ClientDetailsHelper.arrayFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.arrayFromString) ClientDetailsHelper.clientFromString(org.cloudfoundry.identity.uaa.mock.util.ClientDetailsHelper.clientFromString) ResultActions(org.springframework.test.web.servlet.ResultActions) Approval(org.cloudfoundry.identity.uaa.approval.Approval) ClientDetailsModification(org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification) Test(org.junit.jupiter.api.Test)

Aggregations

AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)46 Approval (org.cloudfoundry.identity.uaa.approval.Approval)43 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)34 Authentication (org.springframework.security.core.Authentication)27 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)27 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)25 Test (org.junit.Test)24 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)22 Date (java.util.Date)21 Test (org.junit.jupiter.api.Test)19 IsEmptyString.isEmptyString (org.hamcrest.text.IsEmptyString.isEmptyString)16 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)15 Approval (org.springframework.security.oauth2.provider.approval.Approval)15 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)9 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 Map (java.util.Map)8 HashMap (java.util.HashMap)7 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)7 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)7 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)7