Example usage for org.springframework.security.oauth2.common.exceptions InvalidScopeException InvalidScopeException

List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidScopeException InvalidScopeException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions InvalidScopeException InvalidScopeException.

Prototype

public InvalidScopeException(String msg) 

Source Link

Usage

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();/*  w  w  w . j av  a2 s  .  c  om*/
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

From source file:org.mitre.oauth2.service.impl.DefaultOAuth2ProviderTokenService.java

@Override
public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, TokenRequest authRequest)
        throws AuthenticationException {

    OAuth2RefreshTokenEntity refreshToken = clearExpiredRefreshToken(
            tokenRepository.getRefreshTokenByValue(refreshTokenValue));

    if (refreshToken == null) {
        throw new InvalidTokenException("Invalid refresh token: " + refreshTokenValue);
    }/*from ww w.  java2 s .com*/

    ClientDetailsEntity client = refreshToken.getClient();

    AuthenticationHolderEntity authHolder = refreshToken.getAuthenticationHolder();

    // make sure that the client requesting the token is the one who owns the refresh token
    ClientDetailsEntity requestingClient = clientDetailsService.loadClientByClientId(authRequest.getClientId());
    if (!client.getClientId().equals(requestingClient.getClientId())) {
        tokenRepository.removeRefreshToken(refreshToken);
        throw new InvalidClientException("Client does not own the presented refresh token");
    }

    //Make sure this client allows access token refreshing
    if (!client.isAllowRefresh()) {
        throw new InvalidClientException("Client does not allow refreshing access token!");
    }

    // clear out any access tokens
    if (client.isClearAccessTokensOnRefresh()) {
        tokenRepository.clearAccessTokensForRefreshToken(refreshToken);
    }

    if (refreshToken.isExpired()) {
        tokenRepository.removeRefreshToken(refreshToken);
        throw new InvalidTokenException("Expired refresh token: " + refreshTokenValue);
    }

    OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();

    // get the stored scopes from the authentication holder's authorization request; these are the scopes associated with the refresh token
    Set<String> refreshScopesRequested = new HashSet<>(
            refreshToken.getAuthenticationHolder().getAuthentication().getOAuth2Request().getScope());
    Set<SystemScope> refreshScopes = scopeService.fromStrings(refreshScopesRequested);
    // remove any of the special system scopes
    refreshScopes = scopeService.removeReservedScopes(refreshScopes);

    Set<String> scopeRequested = authRequest.getScope() == null ? new HashSet<String>()
            : new HashSet<>(authRequest.getScope());
    Set<SystemScope> scope = scopeService.fromStrings(scopeRequested);

    // remove any of the special system scopes
    scope = scopeService.removeReservedScopes(scope);

    if (scope != null && !scope.isEmpty()) {
        // ensure a proper subset of scopes
        if (refreshScopes != null && refreshScopes.containsAll(scope)) {
            // set the scope of the new access token if requested
            token.setScope(scopeService.toStrings(scope));
        } else {
            String errorMsg = "Up-scoping is not allowed.";
            logger.error(errorMsg);
            throw new InvalidScopeException(errorMsg);
        }
    } else {
        // otherwise inherit the scope of the refresh token (if it's there -- this can return a null scope set)
        token.setScope(scopeService.toStrings(refreshScopes));
    }

    token.setClient(client);

    if (client.getAccessTokenValiditySeconds() != null) {
        Date expiration = new Date(
                System.currentTimeMillis() + (client.getAccessTokenValiditySeconds() * 1000L));
        token.setExpiration(expiration);
    }

    if (client.isReuseRefreshToken()) {
        // if the client re-uses refresh tokens, do that
        token.setRefreshToken(refreshToken);
    } else {
        // otherwise, make a new refresh token
        OAuth2RefreshTokenEntity newRefresh = createRefreshToken(client, authHolder);
        token.setRefreshToken(newRefresh);

        // clean up the old refresh token
        tokenRepository.removeRefreshToken(refreshToken);
    }

    token.setAuthenticationHolder(authHolder);

    tokenEnhancer.enhance(token, authHolder.getAuthentication());

    tokenRepository.saveAccessToken(token);

    return token;

}

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();//from  ww w.j  a  va  2  s  . c  om
        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.oauth.CheckTokenEndpoint.java

@RequestMapping(value = "/check_token")
@ResponseBody//w  w  w . j a va2s  .  co  m
public Claims checkToken(@RequestParam("token") String value,
        @RequestParam(name = "scopes", required = false, defaultValue = "") List<String> scopes) {

    OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
    if (token == null) {
        throw new InvalidTokenException("Token was not recognised");
    }

    if (token.isExpired()) {
        throw new InvalidTokenException("Token has expired");
    }

    try {
        resourceServerTokenServices.loadAuthentication(value);
    } catch (AuthenticationException x) {
        throw new InvalidTokenException((x.getMessage()));
    }

    Claims response = getClaimsForToken(token.getValue());

    List<String> claimScopes = response.getScope().stream().map(String::toLowerCase)
            .collect(Collectors.toList());

    List<String> missingScopes = new ArrayList<>();
    for (String expectedScope : scopes) {
        if (!claimScopes.contains(expectedScope.toLowerCase())) {
            missingScopes.add(expectedScope);
        }
    }

    if (!missingScopes.isEmpty()) {
        throw new InvalidScopeException(
                "Some requested scopes are missing: " + String.join(",", missingScopes));
    }

    return response;
}