Search in sources :

Example 6 with InvalidScopeException

use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project spring-security-oauth by spring-projects.

the class DefaultTokenServices method createRefreshedAuthentication.

/**
	 * Create a refreshed authentication.
	 * 
	 * @param authentication The authentication.
	 * @param request The scope for the refreshed token.
	 * @return The refreshed authentication.
	 * @throws InvalidScopeException If the scope requested is invalid or wider than the original scope.
	 */
private OAuth2Authentication createRefreshedAuthentication(OAuth2Authentication authentication, TokenRequest request) {
    OAuth2Authentication narrowed = authentication;
    Set<String> scope = request.getScope();
    OAuth2Request clientAuth = authentication.getOAuth2Request().refresh(request);
    if (scope != null && !scope.isEmpty()) {
        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 {
            clientAuth = clientAuth.narrowScope(scope);
        }
    }
    narrowed = new OAuth2Authentication(clientAuth, authentication.getUserAuthentication());
    return narrowed;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Example 7 with InvalidScopeException

use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.

the class OrcidAuthorizationCodeTokenGranter method getOAuth2Authentication.

@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
    Map<String, String> parameters = tokenRequest.getRequestParameters();
    String authorizationCode = parameters.get("code");
    String redirectUri = parameters.get(OAuth2Utils.REDIRECT_URI);
    LOGGER.info("Getting OAuth2 authentication: code={}, redirectUri={}, clientId={}, scope={}", new Object[] { authorizationCode, redirectUri, tokenRequest.getClientId(), tokenRequest.getScope() });
    if (authorizationCode == null) {
        throw new OAuth2Exception("An authorization code must be supplied.");
    }
    //Validate the client is active
    ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(tokenRequest.getClientId());
    orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetails);
    //Validate scopes
    OrcidOauth2AuthoriziationCodeDetail codeDetails = orcidOauth2AuthoriziationCodeDetailDao.find(authorizationCode);
    if (codeDetails == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    } else {
        // Check auth code expiration
        Date tokenCreationDate = codeDetails.getDateCreated();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(tokenCreationDate);
        calendar.add(Calendar.MINUTE, authorizationCodeExpiration);
        Date tokenExpirationDate = calendar.getTime();
        if (tokenExpirationDate.before(new Date())) {
            throw new IllegalArgumentException("Authorization code has expired");
        }
        // Check granted scopes
        Set<String> grantedScopes = codeDetails.getScopes();
        Set<String> requestScopes = tokenRequest.getScope();
        for (String requestScope : requestScopes) {
            if (!grantedScopes.contains(requestScope)) {
                throw new InvalidScopeException("Invalid scopes: " + requestScope + " available scopes for this code are: " + grantedScopes);
            }
        }
    }
    //Consume code        
    OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    if (storedAuth == null) {
        throw new InvalidGrantException("Invalid authorization code: " + authorizationCode);
    }
    OAuth2Request pendingAuthorizationRequest = storedAuth.getOAuth2Request();
    //Regenerate the authorization request but now with the request parameters
    pendingAuthorizationRequest = pendingAuthorizationRequest.createOAuth2Request(parameters);
    LOGGER.info("Found pending authorization request: redirectUri={}, clientId={}, scope={}, is_approved={}", new Object[] { pendingAuthorizationRequest.getRedirectUri(), pendingAuthorizationRequest.getClientId(), pendingAuthorizationRequest.getScope(), pendingAuthorizationRequest.isApproved() });
    // https://jira.springsource.org/browse/SECOAUTH-333
    // This might be null, if the authorization was done without the
    // redirect_uri parameter
    String redirectUriApprovalParameter = pendingAuthorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
    if ((redirectUri != null || redirectUriApprovalParameter != null) && !pendingAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
        throw new RedirectMismatchException("Redirect URI mismatch.");
    }
    String pendingClientId = pendingAuthorizationRequest.getClientId();
    String clientId = client.getClientId();
    LOGGER.info("Comparing client ids: pendingClientId={}, authorizationRequest.clientId={}", pendingClientId, clientId);
    if (clientId != null && !clientId.equals(pendingClientId)) {
        // just a sanity check.
        throw new InvalidClientException("Client ID mismatch");
    }
    Authentication userAuth = storedAuth.getUserAuthentication();
    return new OAuth2Authentication(pendingAuthorizationRequest, userAuth);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) Calendar(java.util.Calendar) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) Date(java.util.Date) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException)

Example 8 with InvalidScopeException

use of org.springframework.security.oauth2.common.exceptions.InvalidScopeException in project ORCID-Source by ORCID.

the class OrcidRefreshTokenTokenGranterTest method tryToCreateRefreshTokenWithInvalidScopesTest.

@Test
public void tryToCreateRefreshTokenWithInvalidScopesTest() {
    // Create token, try to create refresh token with invalid scopes, fail
    long time = System.currentTimeMillis();
    String parentScope = "/person/update";
    String refreshScope = "/orcid-works/read-limited";
    String tokenValue = "parent-token-" + time;
    String refreshTokenValue = "refresh-token-" + time;
    Boolean revokeOld = true;
    Date parentTokenExpiration = new Date(time + 10000);
    Long expireIn = null;
    OrcidOauth2TokenDetail parent = createToken(CLIENT_ID_1, USER_ORCID, tokenValue, refreshTokenValue, parentTokenExpiration, parentScope);
    try {
        generateRefreshToken(parent, null, revokeOld, expireIn, refreshScope);
        fail();
    } catch (InvalidScopeException e) {
        assertTrue(e.getMessage().contains("is not allowed for the parent token"));
    } catch (Exception e) {
        fail();
    }
}
Also used : InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) Date(java.util.Date) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) NoResultException(javax.persistence.NoResultException) InvalidScopeException(org.springframework.security.oauth2.common.exceptions.InvalidScopeException) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Aggregations

InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)8 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)5 ModelAndView (org.springframework.web.servlet.ModelAndView)4 RedirectView (org.springframework.web.servlet.view.RedirectView)4 Date (java.util.Date)3 LockedException (org.orcid.core.security.aop.LockedException)3 RequestInfoForm (org.orcid.pojo.ajaxForm.RequestInfoForm)3 Authentication (org.springframework.security.core.Authentication)3 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)3 Test (org.junit.Test)2 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)2 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)2 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)2 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)2 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)2 Calendar (java.util.Calendar)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 NoResultException (javax.persistence.NoResultException)1 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)1