List of usage examples for org.springframework.security.oauth2.common.util OAuth2Utils USER_OAUTH_APPROVAL
String USER_OAUTH_APPROVAL
To view the source code for org.springframework.security.oauth2.common.util OAuth2Utils USER_OAUTH_APPROVAL.
Click Source Link
From source file:spring.AbstractAuthorizationCodeProviderTests.java
@Test @OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false) public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception { AccessTokenRequest request = context.getAccessTokenRequest(); request.setCurrentUri("http://anywhere"); request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); try {/*from w ww. ja va2s . c o m*/ String code = getAccessTokenProvider().obtainAuthorizationCode(context.getResource(), request); assertNotNull(code); fail("Expected UserRedirectRequiredException"); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details; HttpHeaders headers = getHeadersForAuthorizationRequest(request); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) { form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); for (String scope : details.getScope()) { form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); }//from w w w. ja v a2s. com } else { form.putAll(getParametersForAuthorizeRequest(resource, request)); } authorizationRequestEnhancer.enhance(request, resource, form, headers); final AccessTokenRequest copy = request; final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor(); ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() { @Override public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException { if (response.getHeaders().containsKey("Set-Cookie")) { copy.setCookie(response.getHeaders().getFirst("Set-Cookie")); } return delegate.extractData(response); } }; // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by // subclasses ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap()); if (response.getStatusCode() == HttpStatus.OK) { // Need to re-submit with approval... throw getUserApprovalSignal(resource, request); } URI location = response.getHeaders().getLocation(); String query = location.getQuery(); Map<String, String> map = OAuth2Utils.extractMap(query); if (map.containsKey("state")) { request.setStateKey(map.get("state")); if (request.getPreservedState() == null) { String redirectUri = resource.getRedirectUri(request); if (redirectUri != null) { request.setPreservedState(redirectUri); } else { request.setPreservedState(new Object()); } } } String code = map.get("code"); if (code == null) { throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap()); } request.set("code", code); return code; }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
@Test @OAuth2ContextConfiguration(resource = MyTrustedClient.class, initialize = false) public void testUnauthenticatedAuthorizationRespondsUnauthorized() throws Exception { AccessTokenRequest request = context.getAccessTokenRequest(); request.setCurrentUri("http://anywhere"); request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); try {/*from w ww . j av a 2s . c om*/ String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request); assertNotNull(code); fail("Expected UserRedirectRequiredException"); } catch (HttpClientErrorException e) { assertEquals(HttpStatus.UNAUTHORIZED, e.getStatusCode()); } }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
/** * Obtains the authorization code from the access token request. * * @param details the authenticatoin details * @param request the access token request * @return the authorization code//from www . j av a2 s . c o m * @throws UserRedirectRequiredException when redirection is required * @throws UserApprovalRequiredException when the user requires approval * @throws AccessDeniedException when the user is denied access * @throws OAuth2AccessDeniedException when the user is denied access but we dont want the default Spring Security handling */ public final String obtainAuthorizationCode(final OAuth2ProtectedResourceDetails details, final AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException { GoogleAuthCodeResourceDetails resource; try { resource = (GoogleAuthCodeResourceDetails) details; } catch (ClassCastException ex) { throw new IllegalArgumentException("details is not an instance of class GoogleAuthCodeResourceDetails"); } HttpHeaders headers = getHeadersForAuthorizationRequest(request); MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) { form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); for (String scope : details.getScope()) { form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL)); } } else { form.putAll(getParametersForAuthorizeRequest(resource, request)); } authorizationRequestEnhancer.enhance(request, resource, form, headers); final AccessTokenRequest copy = request; final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor(); ResponseExtractor<ResponseEntity<Void>> extractor = new CookieResponseExtractor(copy, delegate); // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by // subclasses ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap()); if (response.getStatusCode() == HttpStatus.OK) { // Need to re-submit with approval... throw getUserApprovalSignal(resource, request); } URI location = response.getHeaders().getLocation(); String query = location.getQuery(); Map<String, String> map = OAuth2Utils.extractMap(query); if (map.containsKey("state")) { request.setStateKey(map.get("state")); if (request.getPreservedState() == null) { String redirectUri = resource.getRedirectUri(request); if (redirectUri != null) { request.setPreservedState(redirectUri); } else { request.setPreservedState(new Object()); } } } String code = map.get("code"); if (code == null) { throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap()); } request.set("code", code); return code; }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
protected UserApprovalRequiredException getUserApprovalSignal(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {// ww w . ja va2 s . co m String message = String.format("Do you approve the client '%s' to access your resources with scope=%s", resource.getClientId(), resource.getScope()); return new UserApprovalRequiredException(resource.getUserAuthorizationUri(), Collections.singletonMap(OAuth2Utils.USER_OAUTH_APPROVAL, message), resource.getClientId(), resource.getScope()); }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
protected void approveAccessTokenGrant(String currentUri, boolean approved) { AccessTokenRequest request = context.getAccessTokenRequest(); request.setHeaders(getAuthenticatedHeaders()); AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) context.getResource(); if (currentUri != null) { request.setCurrentUri(currentUri); }//from w w w . j av a 2 s . c o m String location = null; try { // First try to obtain the access token... assertNotNull(context.getAccessToken()); fail("Expected UserRedirectRequiredException"); } catch (UserRedirectRequiredException e) { // Expected and necessary, so that the correct state is set up in the request... location = e.getRedirectUri(); } assertTrue(location.startsWith(resource.getUserAuthorizationUri())); assertNull(request.getAuthorizationCode()); verifyAuthorizationPage(context.getRestTemplate(), location); try { // Now try again and the token provider will redirect for user approval... assertNotNull(context.getAccessToken()); fail("Expected UserRedirectRequiredException"); } catch (UserApprovalRequiredException e) { // Expected and necessary, so that the user can approve the grant... location = e.getApprovalUri(); } assertTrue(location.startsWith(resource.getUserAuthorizationUri())); assertNull(request.getAuthorizationCode()); // The approval (will be processed on the next attempt to obtain an access token)... request.set(OAuth2Utils.USER_OAUTH_APPROVAL, "" + approved); }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
/** * Gets the content for the UserApprovalRequire exeption. * * @param resource the resource details objet * @param request the access toke request * @return the exception to be thrown//from w w w . j a v a 2 s . c om */ protected final UserApprovalRequiredException getUserApprovalSignal(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { String message = String.format("Do you approve the client '%s' to access your resources with scope=%s", resource.getClientId(), resource.getScope()); return new UserApprovalRequiredException(resource.getUserAuthorizationUri(), Collections.singletonMap(OAuth2Utils.USER_OAUTH_APPROVAL, message), resource.getClientId(), resource.getScope()); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
@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();// w w w .j a v a2 s. c o m 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(); } }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenLenientWhenAppNotApproved() throws Exception { String clientId = "testclient" + generator.generate(); String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid"; setUpClients(clientId, scopes, scopes, "authorization_code", false); String username = "testuser" + generator.generate(); String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setClientId(clientId); authorizationRequest.setRedirectUri(TEST_REDIRECT_URI); authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid"))); authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token"))); authorizationRequest.setState(state); session.setAttribute("authorizationRequest", authorizationRequest); MvcResult result = getMockMvc()//from w w w . j a v a2s. c o m .perform(post("/oauth/authorize").session(session).with(cookieCsrf()) .param(OAuth2Utils.USER_OAUTH_APPROVAL, "true").param("scope.0", "openid")) .andExpect(status().is3xxRedirection()).andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map query = splitQuery(url); assertNotNull(query.get("code")); String code = ((List<String>) query.get("code")).get(0); assertNotNull(code); }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() throws Exception { String clientId = "testclient" + generator.generate(); String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid"; setUpClients(clientId, scopes, scopes, "authorization_code", false); String username = "testuser" + generator.generate(); String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setClientId(clientId); authorizationRequest.setRedirectUri(TEST_REDIRECT_URI); authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid"))); authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token"))); authorizationRequest.setState(state); session.setAttribute("authorizationRequest", authorizationRequest); MvcResult result = getMockMvc()/*w ww . j av a 2 s .co m*/ .perform(post("/oauth/authorize").session(session).param(OAuth2Utils.USER_OAUTH_APPROVAL, "true") .with(cookieCsrf()).param("scope.0", "openid")) .andExpect(status().is3xxRedirection()).andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map query = splitQuery(url); assertNotNull(query.get("id_token")); assertNotNull(((List) query.get("id_token")).get(0)); assertNotNull(((List) query.get("code")).get(0)); assertNull(query.get("token")); }