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));
}
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);
}
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();
}
}
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));
}
}
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);
}
Aggregations