List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setScope
public void setScope(Collection<String> scope)
From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java
@Override public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) { AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(), inputParams.get(OAuth2Utils.CLIENT_ID), OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false, inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI), OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE))); //Add extension parameters to the 'extensions' map if (inputParams.containsKey("prompt")) { request.getExtensions().put("prompt", inputParams.get("prompt")); }/*from w w w . j ava 2 s . c om*/ if (inputParams.containsKey("nonce")) { request.getExtensions().put("nonce", inputParams.get("nonce")); } if (inputParams.containsKey("claims")) { JsonObject claimsRequest = parseClaimRequest(inputParams.get("claims")); if (claimsRequest != null) { request.getExtensions().put("claims", claimsRequest.toString()); } } if (inputParams.containsKey("request")) { request.getExtensions().put("request", inputParams.get("request")); processRequestObject(inputParams.get("request"), request); } if ((request.getScope() == null || request.getScope().isEmpty())) { if (request.getClientId() != null) { ClientDetails client = clientDetailsService.loadClientByClientId(request.getClientId()); Set<String> clientScopes = client.getScope(); request.setScope(clientScopes); } } return request; }
From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java
@Override public AuthorizationRequest createAuthorizationRequest(Map<String, String> inputParams) { AuthorizationRequest request = new AuthorizationRequest(inputParams, Collections.<String, String>emptyMap(), inputParams.get(OAuth2Utils.CLIENT_ID), OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.SCOPE)), null, null, false, inputParams.get(OAuth2Utils.STATE), inputParams.get(OAuth2Utils.REDIRECT_URI), OAuth2Utils.parseParameterList(inputParams.get(OAuth2Utils.RESPONSE_TYPE))); //Add extension parameters to the 'extensions' map if (inputParams.containsKey(PROMPT)) { request.getExtensions().put(PROMPT, inputParams.get(PROMPT)); }//from w w w .j av a 2 s. com if (inputParams.containsKey(NONCE)) { request.getExtensions().put(NONCE, inputParams.get(NONCE)); } if (inputParams.containsKey(CLAIMS)) { JsonObject claimsRequest = parseClaimRequest(inputParams.get(CLAIMS)); if (claimsRequest != null) { request.getExtensions().put(CLAIMS, claimsRequest.toString()); } } if (inputParams.containsKey(MAX_AGE)) { request.getExtensions().put(MAX_AGE, inputParams.get(MAX_AGE)); } if (inputParams.containsKey(LOGIN_HINT)) { request.getExtensions().put(LOGIN_HINT, inputParams.get(LOGIN_HINT)); } if (inputParams.containsKey(AUD)) { request.getExtensions().put(AUD, inputParams.get(AUD)); } if (inputParams.containsKey(REQUEST)) { request.getExtensions().put(REQUEST, inputParams.get(REQUEST)); processRequestObject(inputParams.get(REQUEST), request); } if (request.getClientId() != null) { try { ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if ((request.getScope() == null || request.getScope().isEmpty())) { Set<String> clientScopes = client.getScope(); request.setScope(clientScopes); } if (request.getExtensions().get(MAX_AGE) == null && client.getDefaultMaxAge() != null) { request.getExtensions().put(MAX_AGE, client.getDefaultMaxAge().toString()); } } catch (OAuth2Exception e) { logger.error("Caught OAuth2 exception trying to test client scopes and max age:", e); } } return request; }
From source file:org.mitre.openid.connect.token.TofuUserApprovalHandler.java
@Override public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { String userId = userAuthentication.getName(); String clientId = authorizationRequest.getClientId(); ClientDetails client = clientDetailsService.loadClientByClientId(clientId); // This must be re-parsed here because SECOAUTH forces us to call things in a strange order if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval"))) { authorizationRequest.setApproved(true); // process scopes from user input Set<String> allowedScopes = Sets.newHashSet(); Map<String, String> approvalParams = authorizationRequest.getApprovalParameters(); Set<String> keys = approvalParams.keySet(); for (String key : keys) { if (key.startsWith("scope_")) { //This is a scope parameter from the approval page. The value sent back should //be the scope string. Check to make sure it is contained in the client's //registered allowed scopes. String scope = approvalParams.get(key); Set<String> approveSet = Sets.newHashSet(scope); //Make sure this scope is allowed for the given client if (systemScopes.scopesMatch(client.getScope(), approveSet)) { // If it's structured, assign the user-specified parameter SystemScope systemScope = systemScopes.getByValue(scope); if (systemScope != null && systemScope.isStructured()) { String paramValue = approvalParams.get("scopeparam_" + scope); allowedScopes.add(scope + ":" + paramValue); // .. and if it's unstructured, we're all set } else { allowedScopes.add(scope); }//from www.j a v a 2 s . c om } } } // inject the user-allowed scopes into the auth request authorizationRequest.setScope(allowedScopes); //Only store an ApprovedSite if the user has checked "remember this decision": String remember = authorizationRequest.getApprovalParameters().get("remember"); if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) { Date timeout = null; if (remember.equals("one-hour")) { // set the timeout to one hour from now Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, 1); timeout = cal.getTime(); } ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout, allowedScopes); String newSiteId = newSite.getId().toString(); authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId); } setAuthTime(authorizationRequest); } return authorizationRequest; }
From source file:org.smartplatforms.openid.connect.token.SmartTofuUserApprovalHandler.java
@Override public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { String userId = userAuthentication.getName(); String clientId = authorizationRequest.getClientId(); ClientDetails client = clientDetailsService.loadClientByClientId(clientId); // This must be re-parsed here because SECOAUTH forces us to call things in a strange order if (Boolean.parseBoolean(authorizationRequest.getApprovalParameters().get("user_oauth_approval")) && authorizationRequest.getExtensions().get(CSRF) != null && authorizationRequest.getExtensions() .get(CSRF).equals(authorizationRequest.getApprovalParameters().get(CSRF))) { authorizationRequest.setApproved(true); // process scopes from user input Set<String> allowedScopes = Sets.newHashSet(); Map<String, String> approvalParams = authorizationRequest.getApprovalParameters(); Set<String> keys = approvalParams.keySet(); for (String key : keys) { if (key.startsWith("scope_")) { //This is a scope parameter from the approval page. The value sent back should //be the scope string. Check to make sure it is contained in the client's //registered allowed scopes. String scope = approvalParams.get(key); Set<String> approveSet = Sets.newHashSet(scope); //Make sure this scope is allowed for the given client if (systemScopes.scopesMatch(client.getScope(), approveSet)) { // If it's structured, assign the user-specified parameter SystemScope systemScope = systemScopes.getByValue(scope); if (systemScope != null && systemScope.isStructured()) { String paramValue = approvalParams.get("scopeparam_" + scope); if (!Strings.isNullOrEmpty(paramValue)) { allowedScopes.add(scope + ":" + paramValue); } else { allowedScopes.add(scope); }/* ww w .j a v a 2s . co m*/ // .. and if it's unstructured, we're all set } else { allowedScopes.add(scope); } } } } // inject the user-allowed scopes into the auth request authorizationRequest.setScope(allowedScopes); //Only store an ApprovedSite if the user has checked "remember this decision": String remember = authorizationRequest.getApprovalParameters().get("remember"); if (!Strings.isNullOrEmpty(remember) && !remember.equals("none")) { Date timeout = null; if (remember.equals("one-hour")) { // set the timeout to one hour from now Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, 1); timeout = cal.getTime(); } ApprovedSite newSite = approvedSiteService.createApprovedSite(clientId, userId, timeout, allowedScopes); String newSiteId = newSite.getId().toString(); authorizationRequest.getExtensions().put(APPROVED_SITE, newSiteId); } setAuthTime(authorizationRequest); } return authorizationRequest; }
From source file:org.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java
/** * @param inputParams/*w w w .j a va 2s .co m*/ * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() == null || !client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } JWTSigningAndValidationService validator = validators.getValidator(client, alg); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client " + client + " and algorithm " + alg); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); // TODO: what if the content is a signed JWT? (#525) if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * NOTE: Claims inside the request object always take precedence over those in the parameter map. */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims JWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim(RESPONSE_TYPE)); if (responseTypes != null && !responseTypes.isEmpty()) { if (!responseTypes.equals(request.getResponseTypes())) { logger.info( "Mismatch between request object and regular parameter for response_type, using request object"); } request.setResponseTypes(responseTypes); } String redirectUri = claims.getStringClaim(REDIRECT_URI); if (redirectUri != null) { if (!redirectUri.equals(request.getRedirectUri())) { logger.info( "Mismatch between request object and regular parameter for redirect_uri, using request object"); } request.setRedirectUri(redirectUri); } String state = claims.getStringClaim(STATE); if (state != null) { if (!state.equals(request.getState())) { logger.info( "Mismatch between request object and regular parameter for state, using request object"); } request.setState(state); } String nonce = claims.getStringClaim(NONCE); if (nonce != null) { if (!nonce.equals(request.getExtensions().get(NONCE))) { logger.info( "Mismatch between request object and regular parameter for nonce, using request object"); } request.getExtensions().put(NONCE, nonce); } String display = claims.getStringClaim(DISPLAY); if (display != null) { if (!display.equals(request.getExtensions().get(DISPLAY))) { logger.info( "Mismatch between request object and regular parameter for display, using request object"); } request.getExtensions().put(DISPLAY, display); } String prompt = claims.getStringClaim(PROMPT); if (prompt != null) { if (!prompt.equals(request.getExtensions().get(PROMPT))) { logger.info( "Mismatch between request object and regular parameter for prompt, using request object"); } request.getExtensions().put(PROMPT, prompt); } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim(SCOPE)); if (scope != null && !scope.isEmpty()) { if (!scope.equals(request.getScope())) { logger.info( "Mismatch between request object and regular parameter for scope, using request object"); } request.setScope(scope); } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim(CLAIMS)); if (claimRequest != null) { if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get(CLAIMS).toString()))) { logger.info( "Mismatch between request object and regular parameter for claims, using request object"); } // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway request.getExtensions().put(CLAIMS, claimRequest.toString()); } String loginHint = claims.getStringClaim(LOGIN_HINT); if (loginHint != null) { if (!loginHint.equals(request.getExtensions().get(LOGIN_HINT))) { logger.info( "Mistmatch between request object and regular parameter for login_hint, using requst object"); } request.getExtensions().put(LOGIN_HINT, loginHint); } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java
/** * @param inputParams/*from ww w.j a va 2s . co m*/ * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); // TODO: check parameter consistency, move keys to constants if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() != null) { if (!client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } } if (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) || alg.equals(JWSAlgorithm.RS512)) { // it's RSA, need to find the JWK URI and fetch the key if (client.getJwksUri() == null) { throw new InvalidClientException( "Client must have a JWKS URI registered to use signed request objects."); } // check JWT signature JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri()); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's JWKS URI: " + client.getJwksUri()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384) || alg.equals(JWSAlgorithm.HS512)) { // it's HMAC, we need to make a validator based on the client secret JwtSigningAndValidationService validator = getSymmetricValidtor(client); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's secret: " + client.getClientSecret()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * Claims precedence order logic: * * if (in Claims): * if (in params): * if (equal): * OK * else (not equal): * error * else (not in params): * add to params * else (not in claims): * we don't care */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims ReadOnlyJWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim("response_type")); if (responseTypes != null && !responseTypes.isEmpty()) { if (request.getResponseTypes() == null || request.getResponseTypes().isEmpty()) { // if it's null or empty, we fill in the value with what we were passed request.setResponseTypes(responseTypes); } else if (!request.getResponseTypes().equals(responseTypes)) { // FIXME: throw an error } } String redirectUri = claims.getStringClaim("redirect_uri"); if (redirectUri != null) { if (request.getRedirectUri() == null) { request.setRedirectUri(redirectUri); } else if (!request.getRedirectUri().equals(redirectUri)) { // FIXME: throw an error } } String state = claims.getStringClaim("state"); if (state != null) { if (request.getState() == null) { request.setState(state); } else if (!request.getState().equals(state)) { // FIXME: throw an error } } String nonce = claims.getStringClaim("nonce"); if (nonce != null) { if (request.getExtensions().get("nonce") == null) { request.getExtensions().put("nonce", nonce); } else if (!request.getExtensions().get("nonce").equals(nonce)) { // FIXME: throw an error } } String display = claims.getStringClaim("display"); if (display != null) { if (request.getExtensions().get("display") == null) { request.getExtensions().put("display", display); } else if (!request.getExtensions().get("display").equals(display)) { // FIXME: throw an error } } String prompt = claims.getStringClaim("prompt"); if (prompt != null) { if (request.getExtensions().get("prompt") == null) { request.getExtensions().put("prompt", prompt); } else if (!request.getExtensions().get("prompt").equals(prompt)) { // FIXME: throw an error } } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); if (scope != null && !scope.isEmpty()) { if (request.getScope() == null || request.getScope().isEmpty()) { request.setScope(scope); } else if (!request.getScope().equals(scope)) { // FIXME: throw an error } } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim("claims")); if (claimRequest != null) { if (request.getExtensions().get("claims") == null) { // we save the string because the object might not serialize request.getExtensions().put("claims", claimRequest.toString()); } else if (parseClaimRequest(request.getExtensions().get("claims").toString()) .equals(claimRequest)) { // FIXME: throw an error } } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
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()// ww w .ja va 2 s .c om .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()//from ww w . ja v a 2 s .c o 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")); }
From source file:org.cloudfoundry.identity.uaa.oauth.UserManagedAuthzApprovalHandler.java
@Override public boolean isApproved(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { String flag = authorizationRequest.getApprovalParameters().get(approvalParameter); boolean userApproval = flag != null && flag.toLowerCase().equals("true"); if (logger.isDebugEnabled()) { StringBuilder builder = new StringBuilder("Looking up user approved authorizations for "); builder.append("client_id=").append(authorizationRequest.getClientId()); builder.append(" and username=").append(userAuthentication.getName()); logger.debug(builder.toString()); }/* ww w .j av a 2s .co m*/ Collection<String> requestedScopes = authorizationRequest.getScope(); // Factor in auto approved scopes Set<String> autoApprovedScopes = new HashSet<>(); BaseClientDetails client = (BaseClientDetails) clientDetailsService .retrieve(authorizationRequest.getClientId()); if (client != null && requestedScopes != null) { autoApprovedScopes.addAll(client.getAutoApproveScopes()); autoApprovedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, autoApprovedScopes); } //translate scope to user scopes - including wild cards if (userApproval) { // Store the scopes that have been approved / denied Date expiry = computeExpiry(); // Get the approved scopes, calculate the denied scope Map<String, String> approvalParameters = authorizationRequest.getApprovalParameters(); Set<String> approvedScopes = new HashSet<>(); approvedScopes.addAll(autoApprovedScopes); boolean foundUserApprovalParameter = false; for (String approvalParameter : approvalParameters.keySet()) { if (approvalParameter.startsWith(SCOPE_PREFIX)) { approvedScopes.add(approvalParameters.get(approvalParameter).substring(SCOPE_PREFIX.length())); foundUserApprovalParameter = true; } } if (foundUserApprovalParameter) { authorizationRequest.setScope(approvedScopes); for (String requestedScope : requestedScopes) { if (approvedScopes.contains(requestedScope)) { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(APPROVED); approvalStore.addApproval(approval); } else { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(DENIED); approvalStore.addApproval(approval); } } } else { // Deny all except auto approved scopes authorizationRequest.setScope(autoApprovedScopes); for (String requestedScope : requestedScopes) { if (!autoApprovedScopes.contains(requestedScope)) { Approval approval = new Approval().setUserId(getUserId(userAuthentication)) .setClientId(authorizationRequest.getClientId()).setScope(requestedScope) .setExpiresAt(expiry).setStatus(DENIED); approvalStore.addApproval(approval); } } } if (userAuthentication.isAuthenticated()) { return true; } } else { // Find the stored approvals for that user and client List<Approval> userApprovals = approvalStore.getApprovals(getUserId(userAuthentication), authorizationRequest.getClientId()); // Look at the scopes and see if they have expired Set<String> validUserApprovedScopes = new HashSet<>(); Set<String> approvedScopes = new HashSet<>(); approvedScopes.addAll(autoApprovedScopes); validUserApprovedScopes.addAll(autoApprovedScopes); Date today = new Date(); for (Approval approval : userApprovals) { if (approval.getExpiresAt().after(today)) { validUserApprovedScopes.add(approval.getScope()); if (approval.getStatus() == APPROVED) { approvedScopes.add(approval.getScope()); } } } if (logger.isDebugEnabled()) { logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); } // If the requested scopes have already been acted upon by the user, // this request is approved if (validUserApprovedScopes.containsAll(requestedScopes) && userAuthentication.isAuthenticated()) { approvedScopes = UaaTokenUtils.retainAutoApprovedScopes(requestedScopes, approvedScopes); // Set only the scopes that have been approved by the user authorizationRequest.setScope(approvedScopes); return true; } } return false; }
From source file:org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler.java
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { String clientId = authorizationRequest.getClientId(); Collection<String> requestedScopes = authorizationRequest.getScope(); Set<String> approvedScopes = new HashSet<String>(); Set<String> validUserApprovedScopes = new HashSet<String>(); if (clientDetailsService != null) { try {/*from www .j a v a2s . c om*/ ClientDetails client = clientDetailsService.loadClientByClientId(clientId); for (String scope : requestedScopes) { if (client.isAutoApprove(scope) || client.isAutoApprove("all")) { approvedScopes.add(scope); } } if (approvedScopes.containsAll(requestedScopes)) { authorizationRequest.setApproved(true); return authorizationRequest; } } catch (ClientRegistrationException e) { logger.warn("Client registration problem prevent autoapproval check for client=" + clientId); } } if (logger.isDebugEnabled()) { StringBuilder builder = new StringBuilder("Looking up user approved authorizations for "); builder.append("client_id=" + clientId); builder.append(" and username=" + userAuthentication.getName()); logger.debug(builder.toString()); } // Find the stored approvals for that user and client Collection<Approval> userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId); // Look at the scopes and see if they have expired Date today = new Date(); for (Approval approval : userApprovals) { if (approval.getExpiresAt().after(today)) { validUserApprovedScopes.add(approval.getScope()); if (approval.getStatus() == ApprovalStatus.APPROVED) { approvedScopes.add(approval.getScope()); } } } if (logger.isDebugEnabled()) { logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes); } // If the requested scopes have already been acted upon by the user, // this request is approved if (validUserApprovedScopes.containsAll(requestedScopes)) { approvedScopes.retainAll(requestedScopes); // Set only the scopes that have been approved by the user authorizationRequest.setScope(approvedScopes); authorizationRequest.setApproved(true); } return authorizationRequest; }