List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidScopeException InvalidScopeException
public InvalidScopeException(String msg, Set<String> validScope)
From source file:org.mitre.oauth2.token.ScopeServiceAwareOAuth2RequestValidator.java
private void validateScope(Set<String> requestedScopes, Set<String> clientScopes) throws InvalidScopeException { if (requestedScopes != null && !requestedScopes.isEmpty()) { if (clientScopes != null && !clientScopes.isEmpty()) { if (!scopeService.scopesMatch(clientScopes, requestedScopes)) { throw new InvalidScopeException("Invalid scope; requested:" + requestedScopes, clientScopes); }/*from www. ja va 2 s .c o m*/ } } }
From source file:org.mitre.oauth2.token.ChainedTokenGranter.java
@Override protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) throws AuthenticationException, InvalidTokenException { // read and load up the existing token String incomingTokenValue = tokenRequest.getRequestParameters().get("token"); OAuth2AccessTokenEntity incomingToken = tokenServices.readAccessToken(incomingTokenValue); // check for scoping in the request, can't up-scope with a chained request Set<String> approvedScopes = incomingToken.getScope(); Set<String> requestedScopes = tokenRequest.getScope(); if (requestedScopes == null) { requestedScopes = new HashSet<>(); }/*from www. java 2s.c o m*/ // do a check on the requested scopes -- if they exactly match the client scopes, they were probably shadowed by the token granter if (client.getScope().equals(requestedScopes)) { requestedScopes = new HashSet<>(); } // if our scopes are a valid subset of what's allowed, we can continue if (approvedScopes.containsAll(requestedScopes)) { if (requestedScopes.isEmpty()) { // if there are no scopes, inherit the original scopes from the token tokenRequest.setScope(approvedScopes); } else { // if scopes were asked for, give only the subset of scopes requested // this allows safe downscoping tokenRequest.setScope(Sets.intersection(requestedScopes, approvedScopes)); } // NOTE: don't revoke the existing access token // create a new access token OAuth2Authentication authentication = new OAuth2Authentication( getRequestFactory().createOAuth2Request(client, tokenRequest), incomingToken.getAuthenticationHolder().getAuthentication().getUserAuthentication()); return authentication; } else { throw new InvalidScopeException("Invalid scope requested in chained request", approvedScopes); } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationRequestManager.java
/** * Apply UAA rules to validate the requested scope. For client credentials grants the valid scopes are actually in * the authorities of the client.// w w w. jav a 2 s.c om * * @see org.springframework.security.oauth2.provider.endpoint.ParametersValidator#validateParameters(java.util.Map, * org.springframework.security.oauth2.provider.ClientDetails) */ @Override public void validateParameters(Map<String, String> parameters, ClientDetails clientDetails) { if (parameters.containsKey("scope")) { Set<String> validScope = clientDetails.getScope(); if ("client_credentials".equals(parameters.get("grant_type"))) { validScope = AuthorityUtils.authorityListToSet(clientDetails.getAuthorities()); } for (String scope : OAuth2Utils.parseParameterList(parameters.get("scope"))) { if (!validScope.contains(scope)) { throw new InvalidScopeException( "Invalid scope: " + scope + ". Did you know that you can get default scopes by simply sending no value?", validScope); } } } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationRequestManager.java
/** * Add or remove scopes derived from the current authenticated user's authorities (if any) * * @param scopes the initial set of scopes from the client registration * @param clientDetails/*from w ww . j av a2 s.c o m*/ * @param collection the users authorities * @return modified scopes adapted according to the rules specified */ private Set<String> checkUserScopes(Set<String> scopes, Collection<? extends GrantedAuthority> authorities, ClientDetails clientDetails) { Set<String> result = new LinkedHashSet<String>(scopes); Set<String> allowed = new LinkedHashSet<String>(AuthorityUtils.authorityListToSet(authorities)); // Add in all default scopes allowed.addAll(defaultScopes); // Find intersection of user authorities, default scopes and client scopes: for (Iterator<String> iter = allowed.iterator(); iter.hasNext();) { String scope = iter.next(); if (!clientDetails.getScope().contains(scope)) { iter.remove(); } } // Weed out disallowed scopes: for (Iterator<String> iter = result.iterator(); iter.hasNext();) { String scope = iter.next(); if (!allowed.contains(scope)) { iter.remove(); } } // Check that a token with empty scope is not going to be granted if (result.isEmpty() && !clientDetails.getScope().isEmpty()) { throw new InvalidScopeException( "Invalid scope (empty) - this user is not allowed any of the requested scopes: " + scopes + " (either you requested a scope that was not allowed or client '" + clientDetails.getClientId() + "' is not allowed to act on behalf of this user)", allowed); } return result; }
From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java
@Override @Transactional(propagation = Propagation.REQUIRED) public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, AuthorizationRequest request) throws AuthenticationException { log.debug("refreshAccessToken(refreshTokenValue:{}, request:{})", refreshTokenValue, request); if (!supportRefreshToken) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); }//from w w w .j ava2 s. c o m AuthorizationGrant authorizationGrant = authorizationGrantRepository.findByRefreshToken(refreshTokenValue); if (authorizationGrant == null) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); } if (!validateLegalGuardianInAuthrizationGrant(authorizationGrant)) { throw new InvalidGrantException( "Authorization grant is missing a valid legal guardian: " + refreshTokenValue); } OAuth2AccessToken accessToken = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false); ExpiringOAuth2RefreshToken refreshToken = (ExpiringOAuth2RefreshToken) accessToken.getRefreshToken(); if (accessToken == null || accessToken.getRefreshToken() == null) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); } String clientId = authorizationGrant.getClientId(); if (clientId == null || !clientId.equals(request.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } if (isExpired(accessToken.getRefreshToken())) { log.info("Removing expired authorization grant with auth key {} for client {}", authorizationGrant.getAuthenticationKey(), authorizationGrant.getClientId()); authorizationGrantRepository.delete(authorizationGrant); throw new InvalidGrantException("Invalid refresh token: " + accessToken.getRefreshToken()); } Set<String> scope = request.getScope(); // if scope exists, we want to narrow the scope and therefore check that scope is a subset of the original scope // else if the scope param is empty, use the old scope from db. if (scope != null && scope.size() > 0) { if (accessToken.getScope() == null || !accessToken.getScope().containsAll(scope)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + scope + ".", accessToken.getScope()); } else if (accessToken.getScope().size() > scope.size()) { // if scope is narrowed, check for already existing accesstoken OAuth2Authentication auth = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope); AuthorizationGrant grant = authorizationGrantRepository .findByAuthenticationKey(authenticationKeyGenerator.extractKey(auth)); log.info("grant: {}", grant); if (grant != null) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + scope + ". An authorization with that scope, client and user already exists.", accessToken.getScope()); } } } else { scope = accessToken.getScope(); } OAuth2Authentication authentication = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope); if (!reuseRefreshToken) { refreshToken = buildRefreshToken(authentication); authorizationGrant.setRefreshToken(refreshToken.getValue()); authorizationGrant.setGrantExpires(refreshToken.getExpiration()); } authorizationGrant = buildAuthorizationGrant(authorizationGrant, refreshToken, authentication); authorizationGrant = authorizationGrantRepository.save(authorizationGrant); OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false); log.debug("Returning from refreshAccessToken"); return token; }
From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java
/** * Create a refreshed authentication./*w ww .j av a2 s.c o m*/ * * @param authentication The authentication. * @param scope The scope for the refreshed token. * @return The refreshed authentication. * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope. */ protected OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, Set<String> scope) { log.debug("createRefreshedAuthentication"); OAuth2Authentication narrowed = authentication; if (scope != null && !scope.isEmpty()) { AuthorizationRequest clientAuth = authentication.getAuthorizationRequest(); Set<String> originalScope = clientAuth.getScope(); if (originalScope == null || !originalScope.containsAll(scope)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + scope + ".", originalScope); } else { narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication()); } } log.debug("returning from createRefreshedAuthentication"); return narrowed; }
From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenServices.java
@Override public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request) throws AuthenticationException { if (null == refreshTokenValue) { throw new InvalidTokenException("Invalid refresh token (empty token)"); }/*w ww . j a va2 s. c om*/ if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) { throw new InvalidGrantException( "Invalid grant type: " + request.getRequestParameters().get("grant_type")); } Map<String, Object> claims = getClaimsForToken(refreshTokenValue); // TODO: Should reuse the access token you get after the first // successful authentication. // You will get an invalid_grant error if your previous token has not // expired yet. // OAuth2RefreshToken refreshToken = // tokenStore.readRefreshToken(refreshTokenValue); // if (refreshToken == null) { // throw new InvalidGrantException("Invalid refresh token: " + // refreshTokenValue); // } String clientId = (String) claims.get(CID); if (clientId == null || !clientId.equals(request.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } String userid = (String) claims.get(USER_ID); // TODO: Need to add a lookup by id so that the refresh token does not // need to contain a name UaaUser user = userDatabase.retrieveUserById(userid); Integer refreshTokenIssuedAt = (Integer) claims.get(IAT); long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l; // If the user changed their password, expire the refresh token if (user.getModified().after(new Date(refreshTokenIssueDate))) { logger.debug("User was last modified at " + user.getModified() + " refresh token was issued at " + new Date(refreshTokenIssueDate)); throw new InvalidTokenException("Invalid refresh token (password changed): " + refreshTokenValue); } Integer refreshTokenExpiry = (Integer) claims.get(EXP); long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l; if (new Date(refreshTokenExpireDate).before(new Date())) { throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at " + new Date(refreshTokenExpireDate)); } @SuppressWarnings("unchecked") ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE); // default request scopes to what is in the refresh token Set<String> requestedScopes = request.getScope(); if (requestedScopes.isEmpty()) { requestedScopes = new HashSet<String>(tokenScopes); } // The user may not request scopes that were not part of the refresh // token if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + requestedScopes + ".", new HashSet<String>(tokenScopes)); } // from this point on, we only care about the scopes requested, not what // is in the refresh token // ensure all requested scopes are approved: either automatically or // explicitly by the user ClientDetails client = clientDetailsService.loadClientByClientId(clientId); String grantType = claims.get(GRANT_TYPE).toString(); checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client), new Date(refreshTokenIssueDate)); // if we have reached so far, issue an access token Integer validity = client.getAccessTokenValiditySeconds(); @SuppressWarnings("unchecked") Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR); Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD)); OAuth2AccessToken accessToken = createAccessToken(user.getId(), user.getUsername(), user.getEmail(), validity != null ? validity.intValue() : accessTokenValiditySeconds, null, requestedScopes, clientId, audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue, additionalAuthorizationInfo, new HashSet<String>()); //TODO populate response types return accessToken; }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServices.java
@Override public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request) throws AuthenticationException { if (null == refreshTokenValue) { throw new InvalidTokenException("Invalid refresh token (empty token)"); }//from w w w.j av a 2 s . c o m if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) { throw new InvalidGrantException( "Invalid grant type: " + request.getRequestParameters().get("grant_type")); } TokenValidation tokenValidation = validateToken(refreshTokenValue); Map<String, Object> claims = tokenValidation.getClaims(); refreshTokenValue = tokenValidation.getJwt().getEncoded(); @SuppressWarnings("unchecked") ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE); if (isRestrictRefreshGrant() && !tokenScopes.contains(UAA_REFRESH_TOKEN)) { throw new InsufficientScopeException(String.format("Expected scope %s is missing", UAA_REFRESH_TOKEN)); } // TODO: Should reuse the access token you get after the first // successful authentication. // You will get an invalid_grant error if your previous token has not // expired yet. // OAuth2RefreshToken refreshToken = // tokenStore.readRefreshToken(refreshTokenValue); // if (refreshToken == null) { // throw new InvalidGrantException("Invalid refresh token: " + // refreshTokenValue); // } String clientId = (String) claims.get(CID); if (clientId == null || !clientId.equals(request.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } String userid = (String) claims.get(USER_ID); String refreshTokenId = (String) claims.get(JTI); String accessTokenId = generateUniqueTokenId(); boolean opaque = TokenConstants.OPAQUE .equals(request.getRequestParameters().get(TokenConstants.REQUEST_TOKEN_FORMAT)); boolean revocable = opaque || (claims.get(REVOCABLE) == null ? false : (Boolean) claims.get(REVOCABLE)); // TODO: Need to add a lookup by id so that the refresh token does not // need to contain a name UaaUser user = userDatabase.retrieveUserById(userid); ClientDetails client = clientDetailsService.loadClientByClientId(clientId); Integer refreshTokenIssuedAt = (Integer) claims.get(IAT); long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l; Integer refreshTokenExpiry = (Integer) claims.get(EXP); long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l; if (new Date(refreshTokenExpireDate).before(new Date())) { throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at " + new Date(refreshTokenExpireDate)); } // default request scopes to what is in the refresh token Set<String> requestedScopes = request.getScope(); if (requestedScopes.isEmpty()) { requestedScopes = new HashSet<>(tokenScopes); } // The user may not request scopes that were not part of the refresh // token if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) { throw new InvalidScopeException( "Unable to narrow the scope of the client authentication to " + requestedScopes + ".", new HashSet<>(tokenScopes)); } // from this point on, we only care about the scopes requested, not what // is in the refresh token // ensure all requested scopes are approved: either automatically or // explicitly by the user String grantType = claims.get(GRANT_TYPE).toString(); checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client)); // if we have reached so far, issue an access token Integer validity = client.getAccessTokenValiditySeconds(); String nonce = (String) claims.get(NONCE); @SuppressWarnings("unchecked") Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR); @SuppressWarnings("unchecked") Map<String, String> externalAttributes = (Map<String, String>) claims.get(EXTERNAL_ATTR); String revocableHashSignature = (String) claims.get(REVOCATION_SIGNATURE); if (hasText(revocableHashSignature)) { String clientSecretForHash = client.getClientSecret(); if (clientSecretForHash != null && clientSecretForHash.split(" ").length > 1) { clientSecretForHash = clientSecretForHash.split(" ")[1]; } String newRevocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash, user); if (!revocableHashSignature.equals(newRevocableHashSignature)) { throw new TokenRevokedException(refreshTokenValue); } } Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD)); int zoneAccessTokenValidity = getZoneAccessTokenValidity(); CompositeAccessToken accessToken = createAccessToken(accessTokenId, user.getId(), user, (claims.get(AUTH_TIME) != null) ? new Date(((Long) claims.get(AUTH_TIME)) * 1000l) : null, validity != null ? validity.intValue() : zoneAccessTokenValidity, null, requestedScopes, clientId, audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue, nonce, additionalAuthorizationInfo, externalAttributes, new HashSet<>(), revocableHashSignature, false, null, //TODO populate response types null, revocable, null, null); DefaultExpiringOAuth2RefreshToken expiringRefreshToken = new DefaultExpiringOAuth2RefreshToken( refreshTokenValue, new Date(refreshTokenExpireDate)); return persistRevocableToken(accessTokenId, refreshTokenId, accessToken, expiringRefreshToken, clientId, user.getId(), opaque, revocable); }
From source file:org.orcid.core.oauth.OrcidClientCredentialsChecker.java
private void validateScope(ClientDetails clientDetails, Set<String> scopes) { if (clientDetails.isScoped()) { Set<String> validScope = clientDetails.getScope(); if (scopes.isEmpty()) { throw new InvalidScopeException("Invalid scope (none)", validScope); } else if (!containsAny(validScope, ScopePathType.ORCID_PROFILE_CREATE, ScopePathType.WEBHOOK, ScopePathType.PREMIUM_NOTIFICATION, ScopePathType.GROUP_ID_RECORD_READ, ScopePathType.GROUP_ID_RECORD_UPDATE) && !scopes.contains(ScopePathType.READ_PUBLIC.value()) && scopes.size() == 1) { throw new InvalidScopeException( "Invalid scope" + (scopes != null && scopes.size() > 1 ? "s: " : ": " + "") + OAuth2Utils.formatParameterList(scopes), validScope);/*from w ww. j av a 2 s . c om*/ } // The Read public does not have to be granted. It's the implied // read level. We let this through, regardless if (scopes.size() == 1 && scopes.iterator().next().equals(ScopePathType.READ_PUBLIC.value())) { return; } for (String scope : scopes) { if (!validScope.contains(scope)) { throw new InvalidScopeException("Invalid scope: " + scope, validScope); } } } }