Search in sources :

Example 1 with UnsupportedGrantTypeException

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

the class TokenEndpoint method postAccessToken.

@RequestMapping(value = "/oauth/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException("There is no client authentication. Try adding an appropriate authentication filter.");
    }
    String clientId = getClientId(principal);
    ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
    if (clientId != null && !clientId.equals("")) {
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }
    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }
    if (!StringUtils.hasText(tokenRequest.getGrantType())) {
        throw new InvalidRequestException("Missing grant type");
    }
    if (tokenRequest.getGrantType().equals("implicit")) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }
    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            logger.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }
    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }
    OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
    }
    return getResponse(token);
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with UnsupportedGrantTypeException

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

the class OrcidClientCredentialEndPointDelegatorImpl method generateToken.

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code, String redirectUri, String grantType, String refreshToken, String state, String authorization, boolean revokeOld, Long expiresIn) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();
    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }
    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao.find(code);
        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }
            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE) || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
            //This will pass through to the token generator as a request param.
            if (authorizationCodeEntity.getNonce() != null) {
                authorizationParameters.put(OrcidOauth2Constants.NONCE, authorizationCodeEntity.getNonce());
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    //If it is a refresh token request, set the needed authorization parameters
    if (OrcidOauth2Constants.REFRESH_TOKEN.equals(grantType)) {
        authorizationParameters.put(OrcidOauth2Constants.AUTHORIZATION, authorization);
        authorizationParameters.put(OrcidOauth2Constants.REVOKE_OLD, String.valueOf(revokeOld));
        authorizationParameters.put(OrcidOauth2Constants.EXPIRES_IN, String.valueOf(expiresIn));
        authorizationParameters.put(OrcidOauth2Constants.REFRESH_TOKEN, String.valueOf(refreshToken));
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(authorizationParameters);
    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);
    //Need to change this to either the DefaultTokenType or start using a different token type.
    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object[] params = { grantType };
    if (token == null) {
        LOGGER.info("Unsupported grant type for OAuth2: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info("OAuth2 access token granted: clientId={}, grantType={}, code={}, scopes={}, state={}, redirectUri={}, token={}", new Object[] { clientId, grantType, code, scopes, state, redirectUri, token });
    return token;
}
Also used : AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) HashMap(java.util.HashMap) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)

Example 3 with UnsupportedGrantTypeException

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

the class InternalClientCredentialEndPointDelegatorImpl method obtainOauth2Token.

@Override
@Transactional
public Response obtainOauth2Token(String authorization, MultivaluedMap<String, String> formParams) {
    String clientId = formParams.getFirst("client_id");
    String scopeList = formParams.getFirst("scope");
    String grantType = formParams.getFirst("grant_type");
    // Verify it is a client_credentials grant type request
    if (!OrcidOauth2Constants.GRANT_TYPE_CLIENT_CREDENTIALS.equals(grantType)) {
        Object[] params = { grantType };
        throw new UnsupportedGrantTypeException(localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    Authentication client = getClientAuthentication();
    if (!client.isAuthenticated()) {
        LOGGER.info("Not authenticated for OAuth2: clientId={}, grantType={}, scope={}", new Object[] { clientId, grantType, scopeList });
        throw new InsufficientAuthenticationException(localeManager.resolveMessage("apiError.client_not_authenticated.exception"));
    }
    Set<String> scopes = new HashSet<String>();
    if (StringUtils.isNotEmpty(scopeList)) {
        scopes = OAuth2Utils.parseParameterList(scopeList);
    }
    // Verify it is requesting an internal scope
    HashSet<String> filteredScopes = new HashSet<String>();
    for (String scope : scopes) {
        ScopePathType scopeType = ScopePathType.fromValue(scope);
        if (scopeType.isInternalScope()) {
            filteredScopes.add(scope);
        }
    }
    if (filteredScopes.isEmpty()) {
        String message = localeManager.resolveMessage("apiError.9015.developerMessage", new Object[] {});
        throw new OrcidInvalidScopeException(message);
    }
    OAuth2AccessToken token = generateToken(client, scopes, null, null, grantType, null, null, null, false, 0L);
    return getResponse(token);
}
Also used : ScopePathType(org.orcid.jaxb.model.message.ScopePathType) Authentication(org.springframework.security.core.Authentication) OrcidInvalidScopeException(org.orcid.core.exception.OrcidInvalidScopeException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with UnsupportedGrantTypeException

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

the class OAuthErrorUtilsTest method testGetOAuthErrorForUnsupportedGrantTypeException.

@Test
public void testGetOAuthErrorForUnsupportedGrantTypeException() {
    OAuthError error = OAuthErrorUtils.getOAuthError(new UnsupportedGrantTypeException("message here"));
    assertEquals(OAuthError.UNSUPPORTED_GRANT_TYPE, error.getError());
    assertEquals(Status.BAD_REQUEST, error.getResponseStatus());
    assertEquals("message here", error.getErrorDescription());
}
Also used : UnsupportedGrantTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException) Test(org.junit.Test)

Aggregations

UnsupportedGrantTypeException (org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)3 InsufficientAuthenticationException (org.springframework.security.authentication.InsufficientAuthenticationException)2 Authentication (org.springframework.security.core.Authentication)2 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)2 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Test (org.junit.Test)1 OrcidInvalidScopeException (org.orcid.core.exception.OrcidInvalidScopeException)1 ScopePathType (org.orcid.jaxb.model.message.ScopePathType)1 OrcidOauth2AuthoriziationCodeDetail (org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail)1 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)1 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)1 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)1 InvalidRequestException (org.springframework.security.oauth2.common.exceptions.InvalidRequestException)1 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)1 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)1 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)1 Transactional (org.springframework.transaction.annotation.Transactional)1 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)1