Search in sources :

Example 21 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception 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={}, clientId={}, scope={}", new Object[] { authorizationCode, 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) {
        if (Features.REVOKE_TOKEN_ON_CODE_REUSE.isActive()) {
            int numDisabled = orcidOauthTokenDetailService.disableAccessTokenByCodeAndClient(authorizationCode, tokenRequest.getClientId(), RevokeReason.AUTH_CODE_REUSED);
            if (numDisabled > 0) {
                throw new InvalidGrantException("Reused authorization code: " + authorizationCode);
            }
        }
        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;
    try {
        storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode);
    } catch (InvalidGrantException e) {
        throw e;
    }
    OAuth2Request pendingAuthorizationRequest = storedAuth.getOAuth2Request();
    // Regenerate the authorization request but now with the request parameters
    pendingAuthorizationRequest = pendingAuthorizationRequest.createOAuth2Request(parameters);
    LOGGER.debug("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();
    if (clientId != null && !clientId.equals(pendingClientId)) {
        LOGGER.error("Exception exchanging authentication code {}, client ID mismatch: pendingClientId={}, authorizationRequest.clientId={}", new Object[] { authorizationCode, pendingClientId, clientId });
        // 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 22 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class OAuth2ClientAuthenticationProcessingFilterTests method testDeniedToken.

@Test
public void testDeniedToken() throws Exception {
    filter.setRestTemplate(restTemplate);
    Mockito.when(restTemplate.getAccessToken()).thenThrow(new OAuth2Exception("User denied acess token"));
    expected.expect(BadCredentialsException.class);
    filter.attemptAuthentication(null, null);
}
Also used : OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Example 23 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class DefaultOAuth2SerializationServiceTests method testExceptionDeserialization.

@Test
public void testExceptionDeserialization() throws Exception {
    Map<String, String> exception = MapBuilder.create("error", "invalid_client").add("error_description", "FOO").build();
    OAuth2Exception result = OAuth2Exception.valueOf(exception);
    // System.err.println(result);
    assertEquals("FOO", result.getMessage());
    assertEquals("invalid_client", result.getOAuth2ErrorCode());
    assertTrue(result instanceof InvalidClientException);
}
Also used : InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Example 24 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class JsonSerializationTests method testExceptionDeserialization.

@Test
public void testExceptionDeserialization() throws Exception {
    String exception = "{\"error\": \"invalid_client\", \"error_description\": \"FOO\", \"foo\": \"bar\"}";
    OAuth2Exception result = new ObjectMapper().readValue(exception, OAuth2Exception.class);
    // System.err.println(result);
    assertEquals("FOO", result.getMessage());
    assertEquals("invalid_client", result.getOAuth2ErrorCode());
    assertEquals("{foo=bar}", result.getAdditionalInformation().toString());
    assertTrue(result instanceof InvalidClientException);
}
Also used : InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 25 with OAuth2Exception

use of org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception in project spring-security-oauth by spring-projects.

the class OAuth2ExceptionDeserializerTests method readValueUndefinedException.

@Test
public void readValueUndefinedException() throws Exception {
    String accessToken = createResponse("notdefinedcode");
    OAuth2Exception result = mapper.readValue(accessToken, OAuth2Exception.class);
    assertEquals(DETAILS, result.getMessage());
    assertEquals(null, result.getAdditionalInformation());
}
Also used : OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) Test(org.junit.Test)

Aggregations

OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)57 Test (org.junit.Test)15 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)13 AuthenticationException (org.springframework.security.core.AuthenticationException)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)11 Authentication (org.springframework.security.core.Authentication)9 HashMap (java.util.HashMap)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)7 OAuth2Exception (org.maxkey.authz.oauth2.common.exceptions.OAuth2Exception)7 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)7 ModelAndView (org.springframework.web.servlet.ModelAndView)7 RedirectView (org.springframework.web.servlet.view.RedirectView)7 AccessDeniedException (org.springframework.security.access.AccessDeniedException)6 InsufficientScopeException (org.springframework.security.oauth2.common.exceptions.InsufficientScopeException)6 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 Date (java.util.Date)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 ResponseEntity (org.springframework.http.ResponseEntity)5 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)5