Search in sources :

Example 6 with OAuth2Exception

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

the class OrcidOAuth2AuthenticationEntryPoint method handleAsOrcidError.

public void handleAsOrcidError(HttpServletRequest request, HttpServletResponse response, Exception authException) throws IOException, ServletException {
    try {
        ResponseEntity<OAuth2Exception> result = exceptionTranslator.translate(authException);
        result = enhanceResponse(result, authException);
        OrcidError orcidError = new OrcidError();
        orcidError.setResponseCode(result.getStatusCode().value());
        orcidError.setDeveloperMessage(result.getBody().getLocalizedMessage());
        ResponseEntity<OrcidError> errorResponseEntity = new ResponseEntity<>(orcidError, result.getHeaders(), result.getStatusCode());
        exceptionRenderer.handleHttpEntityResponse(errorResponseEntity, new ServletWebRequest(request, response));
        response.flushBuffer();
    } catch (ServletException e) {
        // (even if there is one)
        if (handlerExceptionResolver.resolveException(request, response, this, e) == null) {
            throw e;
        }
    } catch (IOException e) {
        throw e;
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        // Wrap other Exceptions. These are not expected to happen
        throw new RuntimeException(e);
    }
}
Also used : ServletException(javax.servlet.ServletException) OrcidError(org.orcid.jaxb.model.error_v2.OrcidError) ResponseEntity(org.springframework.http.ResponseEntity) IOException(java.io.IOException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) AuthenticationException(org.springframework.security.core.AuthenticationException)

Example 7 with OAuth2Exception

use of org.springframework.security.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={}, 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 OAuth2Exception

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

the class OAuth2ClientAuthenticationProcessingFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    OAuth2AccessToken accessToken;
    try {
        accessToken = restTemplate.getAccessToken();
    } catch (OAuth2Exception e) {
        BadCredentialsException bad = new BadCredentialsException("Could not obtain access token", e);
        publish(new OAuth2AuthenticationFailureEvent(bad));
        throw bad;
    }
    try {
        OAuth2Authentication result = tokenServices.loadAuthentication(accessToken.getValue());
        if (authenticationDetailsSource != null) {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, accessToken.getValue());
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType());
            result.setDetails(authenticationDetailsSource.buildDetails(request));
        }
        publish(new AuthenticationSuccessEvent(result));
        return result;
    } catch (InvalidTokenException e) {
        BadCredentialsException bad = new BadCredentialsException("Could not obtain user details from token", e);
        publish(new OAuth2AuthenticationFailureEvent(bad));
        throw bad;
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) AuthenticationSuccessEvent(org.springframework.security.authentication.event.AuthenticationSuccessEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 9 with OAuth2Exception

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

the class OAuth2ErrorHandler method handleError.

public void handleError(final ClientHttpResponse response) throws IOException {
    if (!HttpStatus.Series.CLIENT_ERROR.equals(response.getStatusCode().series())) {
        // We should only care about 400 level errors. Ex: A 500 server error shouldn't
        // be an oauth related error.
        errorHandler.handleError(response);
    } else {
        // Need to use buffered response because input stream may need to be consumed multiple times.
        ClientHttpResponse bufferedResponse = new ClientHttpResponse() {

            private byte[] lazyBody;

            public HttpStatus getStatusCode() throws IOException {
                return response.getStatusCode();
            }

            public synchronized InputStream getBody() throws IOException {
                if (lazyBody == null) {
                    InputStream bodyStream = response.getBody();
                    if (bodyStream != null) {
                        lazyBody = FileCopyUtils.copyToByteArray(bodyStream);
                    } else {
                        lazyBody = new byte[0];
                    }
                }
                return new ByteArrayInputStream(lazyBody);
            }

            public HttpHeaders getHeaders() {
                return response.getHeaders();
            }

            public String getStatusText() throws IOException {
                return response.getStatusText();
            }

            public void close() {
                response.close();
            }

            public int getRawStatusCode() throws IOException {
                return response.getRawStatusCode();
            }
        };
        try {
            HttpMessageConverterExtractor<OAuth2Exception> extractor = new HttpMessageConverterExtractor<OAuth2Exception>(OAuth2Exception.class, messageConverters);
            try {
                OAuth2Exception oauth2Exception = extractor.extractData(bufferedResponse);
                if (oauth2Exception != null) {
                    // gh-875
                    if (oauth2Exception.getClass() == UserDeniedAuthorizationException.class && bufferedResponse.getStatusCode().equals(HttpStatus.FORBIDDEN)) {
                        oauth2Exception = new OAuth2AccessDeniedException(oauth2Exception.getMessage());
                    }
                    // than the header does, so just re-throw it here.
                    throw oauth2Exception;
                }
            } catch (RestClientException e) {
            // ignore
            } catch (HttpMessageConversionException e) {
            // ignore
            }
            // first try: www-authenticate error
            List<String> authenticateHeaders = bufferedResponse.getHeaders().get("WWW-Authenticate");
            if (authenticateHeaders != null) {
                for (String authenticateHeader : authenticateHeaders) {
                    maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.BEARER_TYPE);
                    maybeThrowExceptionFromHeader(authenticateHeader, OAuth2AccessToken.OAUTH2_TYPE);
                }
            }
            // then delegate to the custom handler
            errorHandler.handleError(bufferedResponse);
        } catch (InvalidTokenException ex) {
            // Special case: an invalid token can be renewed so tell the caller what to do
            throw new AccessTokenRequiredException(resource);
        } catch (OAuth2Exception ex) {
            if (!ex.getClass().equals(OAuth2Exception.class)) {
                // rethrow
                throw ex;
            }
            // This is not an exception that is really understood, so allow our delegate
            // to handle it in a non-oauth way
            errorHandler.handleError(bufferedResponse);
        }
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) UserDeniedAuthorizationException(org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 10 with OAuth2Exception

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

the class OAuth2ErrorHandler method maybeThrowExceptionFromHeader.

private void maybeThrowExceptionFromHeader(String authenticateHeader, String headerType) {
    headerType = headerType.toLowerCase();
    if (authenticateHeader.toLowerCase().startsWith(headerType)) {
        Map<String, String> headerEntries = StringSplitUtils.splitEachArrayElementAndCreateMap(StringSplitUtils.splitIgnoringQuotes(authenticateHeader.substring(headerType.length()), ','), "=", "\"");
        OAuth2Exception ex = OAuth2Exception.valueOf(headerEntries);
        if (ex instanceof InvalidTokenException) {
            // Special case: an invalid token can be renewed so tell the caller what to do
            throw new AccessTokenRequiredException(resource);
        }
        throw ex;
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Aggregations

OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)23 Test (org.junit.Test)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)8 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)7 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)6 ClientDetailsService (org.springframework.security.oauth2.provider.ClientDetailsService)6 BaseClientDetails (org.springframework.security.oauth2.provider.client.BaseClientDetails)6 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)4 IOException (java.io.IOException)3 Date (java.util.Date)3 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)3 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)3 InvalidClientException (org.springframework.security.oauth2.common.exceptions.InvalidClientException)3 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)3 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)3 ModelAndView (org.springframework.web.servlet.ModelAndView)3 ServletException (javax.servlet.ServletException)2 ResponseEntity (org.springframework.http.ResponseEntity)2 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)2 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2