List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setRequestParameters
public void setRequestParameters(Map<String, String> requestParameters)
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testLoadAuthenticationForAUser() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from w w w .j a v a2 s . co m*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals(username, loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = (UaaPrincipal) defaultUserAuthentication.getPrincipal(); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals(username, userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void opaque_tokens_validate_signature() throws Exception { defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token"))); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);// w ww . ja v a 2 s. co m OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertNotNull(accessToken); assertTrue("Token should be composite token", accessToken instanceof CompositeAccessToken); CompositeAccessToken composite = (CompositeAccessToken) accessToken; assertThat("id_token should be JWT, thus longer than 36 characters", composite.getIdTokenValue().length(), greaterThan(36)); assertThat("Opaque access token must be shorter than 37 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat("Opaque refresh token must be shorter than 37 characters", accessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36)); Map<String, String> keys = new HashMap<>(); keys.put("otherKey", "unc0uf98gv89egh4v98749978hv"); tokenPolicy.setKeys(keys); tokenPolicy.setActiveKeyId("otherKey"); IdentityZoneHolder.get().getConfig().setTokenPolicy(tokenPolicy); expectedEx.expect(InvalidTokenException.class); expectedEx.expectMessage("Invalid key ID: testKey"); tokenServices.validateToken(accessToken.getValue()); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testLoad_Opaque_AuthenticationForAUser() { defaultClient.setAutoApproveScopes(singleton("true")); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token"))); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);// w ww . j av a 2 s . c om OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertNotNull(accessToken); assertTrue("Token should be composite token", accessToken instanceof CompositeAccessToken); CompositeAccessToken composite = (CompositeAccessToken) accessToken; assertThat("id_token should be JWT, thus longer than 36 characters", composite.getIdTokenValue().length(), greaterThan(36)); assertThat("Opaque access token must be shorter than 37 characters", accessToken.getValue().length(), lessThanOrEqualTo(36)); assertThat("Opaque refresh token must be shorter than 37 characters", accessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36)); String accessTokenValue = tokenProvisioning.retrieve(composite.getValue()).getValue(); Map<String, Object> accessTokenClaims = tokenServices.validateToken(accessTokenValue).getClaims(); assertEquals(true, accessTokenClaims.get(ClaimConstants.REVOCABLE)); String refreshTokenValue = tokenProvisioning.retrieve(composite.getRefreshToken().getValue()).getValue(); Map<String, Object> refreshTokenClaims = tokenServices.validateToken(refreshTokenValue).getClaims(); assertEquals(true, refreshTokenClaims.get(ClaimConstants.REVOCABLE)); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities()); assertEquals(username, loadedAuthentication.getName()); UaaPrincipal uaaPrincipal = (UaaPrincipal) defaultUserAuthentication.getPrincipal(); assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); Authentication userAuth = loadedAuthentication.getUserAuthentication(); assertEquals(username, userAuth.getName()); assertEquals(uaaPrincipal, userAuth.getPrincipal()); assertTrue(userAuth.isAuthenticated()); Map<String, String> params = new HashedMap(); params.put("grant_type", "refresh_token"); params.put("client_id", CLIENT_ID); OAuth2AccessToken newAccessToken = tokenServices.refreshAccessToken(composite.getRefreshToken().getValue(), new TokenRequest(params, CLIENT_ID, Collections.EMPTY_SET, "refresh_token")); System.out.println("newAccessToken = " + newAccessToken); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testLoadAuthenticationForAClient() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, CLIENT_CREDENTIALS); authorizationRequest.setRequestParameters(azParameters); OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null);/*from w w w. j av a2s. c o m*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue()); assertThat("Client authorities match.", loadedAuthentication.getAuthorities(), containsInAnyOrder( AuthorityUtils.commaSeparatedStringToAuthorityList(CLIENT_AUTHORITIES).toArray())); assertEquals(CLIENT_ID, loadedAuthentication.getName()); assertEquals(CLIENT_ID, loadedAuthentication.getPrincipal()); assertNull(loadedAuthentication.getDetails()); assertNull(loadedAuthentication.getUserAuthentication()); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test(expected = InvalidTokenException.class) public void testLoadAuthenticationWithAnExpiredToken() throws InterruptedException { BaseClientDetails shortExpiryClient = defaultClient; shortExpiryClient.setAccessTokenValiditySeconds(1); clientDetailsService.setClientDetailsStore(Collections.singletonMap(CLIENT_ID, shortExpiryClient)); AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from w w w . ja va2s. co m*/ OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); assertThat(accessToken, validFor(is(1))); Thread.sleep(1000l); tokenServices.loadAuthentication(accessToken.getValue()); }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java
@Test public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() { AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes); authorizationRequest.setResourceIds(new HashSet<>(resourceIds)); Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters()); azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE); azParameters.put("authorities", "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}"); authorizationRequest.setRequestParameters(azParameters); Authentication userAuthentication = defaultUserAuthentication; OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication);/*from w ww.j a va 2 s .c om*/ OAuth2AccessToken token = tokenServices.createAccessToken(authentication); this.assertCommonUserAccessTokenProperties(token); assertThat(token, issuerUri(is(ISSUER_URI))); assertThat(token, scope(is(requestedAuthScopes))); assertThat(token, validFor(is(60 * 60 * 12))); OAuth2RefreshToken refreshToken = token.getRefreshToken(); this.assertCommonUserRefreshTokenProperties(refreshToken); assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI))); assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30))); this.assertCommonEventProperties(token, userId, buildJsonString(requestedAuthScopes)); Map<String, String> azMap = new LinkedHashMap<>(); azMap.put("external_group", "domain\\group1"); azMap.put("external_id", "abcd1234"); assertEquals(azMap, token.getAdditionalInformation().get("az_attr")); }
From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java
@RequestMapping(value = "/confirm_access", method = RequestMethod.GET) public ModelAndView loginGetHandler(HttpServletRequest request, HttpServletResponse response, ModelAndView mav, @RequestParam("client_id") String clientId, @RequestParam("scope") String scope, @RequestParam("redirect_uri") String redirectUri) { OrcidProfile profile = orcidProfileManager.retrieveOrcidProfile(getCurrentUserOrcid(), LoadOptions.BIO_ONLY);/*w w w .j av a2s .co m*/ clientId = (clientId != null) ? clientId.trim() : clientId; scope = (scope != null) ? scope.trim().replaceAll(" +", " ") : scope; redirectUri = (redirectUri != null) ? redirectUri.trim() : redirectUri; Boolean justRegistered = (Boolean) request.getSession().getAttribute(OrcidOauth2Constants.JUST_REGISTERED); if (justRegistered != null) { request.getSession().removeAttribute(OrcidOauth2Constants.JUST_REGISTERED); mav.addObject(OrcidOauth2Constants.JUST_REGISTERED, justRegistered); } String clientName = ""; String clientDescription = ""; String clientGroupName = ""; String clientWebsite = ""; boolean usePersistentTokens = false; ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId); clientName = clientDetails.getClientName() == null ? "" : clientDetails.getClientName(); clientDescription = clientDetails.getClientDescription() == null ? "" : clientDetails.getClientDescription(); clientWebsite = clientDetails.getClientWebsite() == null ? "" : clientDetails.getClientWebsite(); // validate client scopes try { authorizationEndpoint.validateScope(scope, clientDetails); orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails); } catch (InvalidScopeException ise) { String redirectUriWithParams = redirectUri; redirectUriWithParams += "?error=invalid_scope&error_description=" + ise.getMessage(); RedirectView rView = new RedirectView(redirectUriWithParams); ModelAndView error = new ModelAndView(); error.setView(rView); return error; } catch (LockedException le) { String redirectUriWithParams = redirectUri; redirectUriWithParams += "?error=client_locked&error_description=" + le.getMessage(); RedirectView rView = new RedirectView(redirectUriWithParams); ModelAndView error = new ModelAndView(); error.setView(rView); return error; } // Check if the client has persistent tokens enabled if (clientDetails.isPersistentTokensEnabled()) { usePersistentTokens = true; } if (usePersistentTokens) { boolean tokenAlreadyExists = tokenServices.tokenAlreadyExists(clientId, getEffectiveUserOrcid(), OAuth2Utils.parseParameterList(scope)); if (tokenAlreadyExists) { AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession() .getAttribute("authorizationRequest"); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Map<String, String> requestParams = new HashMap<String, String>(); copyRequestParameters(request, requestParams); Map<String, String> approvalParams = new HashMap<String, String>(); requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN); // Check if the client have persistent tokens enabled requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false"); if (hasPersistenTokensEnabled(clientId)) { // Then check if the client granted the persistent token requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true"); } // Session status SimpleSessionStatus status = new SimpleSessionStatus(); authorizationRequest.setRequestParameters(requestParams); // Authorization request model Map<String, Object> model = new HashMap<String, Object>(); model.put("authorizationRequest", authorizationRequest); // Approve RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth); ModelAndView authCodeView = new ModelAndView(); authCodeView.setView(view); return authCodeView; } } if (clientDetails.getClientType() == null) { clientGroupName = PUBLIC_MEMBER_NAME; } else if (!PojoUtil.isEmpty(clientDetails.getGroupProfileId())) { ProfileEntity groupProfile = profileEntityCacheManager.retrieve(clientDetails.getGroupProfileId()); clientGroupName = groupProfile.getCreditName(); } // If the group name is empty, use the same as the client name, since it // should be a SSO user if (StringUtils.isBlank(clientGroupName)) { clientGroupName = clientName; } mav.addObject("profile", profile); mav.addObject("client_name", clientName); mav.addObject("client_description", clientDescription); mav.addObject("client_group_name", clientGroupName); mav.addObject("client_website", clientWebsite); mav.addObject("scopes", ScopePathType.getScopesFromSpaceSeparatedString(scope)); mav.addObject("scopesString", scope); mav.addObject("hideUserVoiceScript", true); mav.addObject("usePersistentTokens", usePersistentTokens); mav.setViewName("confirm-oauth-access"); return mav; }
From source file:org.orcid.frontend.web.controllers.OauthConfirmAccessController.java
@RequestMapping(value = { "/custom/authorize.json" }, method = RequestMethod.POST) public @ResponseBody OauthAuthorizeForm authorize(HttpServletRequest request, HttpServletResponse response, @RequestBody OauthAuthorizeForm form) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); AuthorizationRequest authorizationRequest = (AuthorizationRequest) request.getSession() .getAttribute("authorizationRequest"); Map<String, String> requestParams = new HashMap<String, String>( authorizationRequest.getRequestParameters()); Map<String, String> approvalParams = new HashMap<String, String>(); // Add the persistent token information if (form.getApproved()) { requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "true"); } else {/*from ww w. j a va 2s. com*/ requestParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false"); approvalParams.put(OAuth2Utils.USER_OAUTH_APPROVAL, "false"); } requestParams.put(OrcidOauth2Constants.TOKEN_VERSION, OrcidOauth2Constants.PERSISTENT_TOKEN); // Check if the client have persistent tokens enabled requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "false"); if (hasPersistenTokensEnabled(form.getClientId().getValue())) // Then check if the client granted the persistent token if (form.getPersistentTokenEnabled()) requestParams.put(OrcidOauth2Constants.GRANT_PERSISTENT_TOKEN, "true"); // Session status SimpleSessionStatus status = new SimpleSessionStatus(); authorizationRequest.setRequestParameters(requestParams); // Authorization request model Map<String, Object> model = new HashMap<String, Object>(); model.put("authorizationRequest", authorizationRequest); // Approve RedirectView view = (RedirectView) authorizationEndpoint.approveOrDeny(approvalParams, model, status, auth); form.setRedirectUri(Text.valueOf(view.getUrl())); SavedRequest savedRequest = new HttpSessionRequestCache().getRequest(request, response); if (savedRequest != null) LOGGER.info("OauthConfirmAccessController original request: " + savedRequest.getRedirectUrl()); LOGGER.info("OauthConfirmAccessController form.getRedirectUri being sent to client browser: " + form.getRedirectUri()); return form; }