Search in sources :

Example 6 with InvalidTokenException

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

the class OrcidRandomValueTokenServicesTest method tokenExpiredDoesntWorkTest.

@Test
public void tokenExpiredDoesntWorkTest() {
    OrcidOauth2TokenDetail expiredToken = new OrcidOauth2TokenDetail();
    expiredToken.setApproved(true);
    expiredToken.setAuthenticationKey("authentication-key");
    expiredToken.setClientDetailsId("4444-4444-4444-4441");
    expiredToken.setProfile(new ProfileEntity("4444-4444-4444-4442"));
    expiredToken.setResourceId("orcid");
    expiredToken.setScope("/read-limited");
    expiredToken.setTokenExpiration(new Date(System.currentTimeMillis() - 1000));
    expiredToken.setTokenValue("token-value");
    orcidOauthTokenDetailService.removeConflictsAndCreateNew(expiredToken);
    // The first time we try to use it, we get a InvalidTokenException with message Access token expired: token-value
    try {
        tokenServices.loadAuthentication("token-value");
        fail();
    } catch (InvalidTokenException e) {
        assertEquals("Access token expired: token-value", e.getMessage());
    }
    // Second time we try to use it, we get a InvalidTokenException with message Invalid access token: token-value
    try {
        tokenServices.loadAuthentication("token-value");
        fail();
    } catch (InvalidTokenException e) {
        assertEquals("Invalid access token: token-value", e.getMessage());
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 7 with InvalidTokenException

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

the class OrcidTokenStoreServiceImpl method getOAuth2AuthenticationFromDetails.

private OAuth2Authentication getOAuth2AuthenticationFromDetails(OrcidOauth2TokenDetail details) {
    if (details != null) {
        ClientDetailsEntity clientDetailsEntity = clientDetailsEntityCacheManager.retrieve(details.getClientDetailsId());
        Authentication authentication = null;
        AuthorizationRequest request = null;
        if (clientDetailsEntity != null) {
            //Check member is not locked                
            orcidOAuth2RequestValidator.validateClientIsEnabled(clientDetailsEntity);
            Set<String> scopes = OAuth2Utils.parseParameterList(details.getScope());
            request = new AuthorizationRequest(clientDetailsEntity.getClientId(), scopes);
            request.setAuthorities(clientDetailsEntity.getAuthorities());
            Set<String> resourceIds = new HashSet<>();
            resourceIds.add(details.getResourceId());
            request.setResourceIds(resourceIds);
            request.setApproved(details.isApproved());
            ProfileEntity profile = details.getProfile();
            if (profile != null) {
                authentication = new OrcidOauth2UserAuthentication(profile, details.isApproved());
            }
        }
        return new OrcidOAuth2Authentication(request, authentication, details.getTokenValue());
    }
    throw new InvalidTokenException("Token not found");
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) AuthorizationRequest(org.springframework.security.oauth2.provider.AuthorizationRequest) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OrcidOauth2UserAuthentication(org.orcid.core.oauth.OrcidOauth2UserAuthentication) OrcidOAuth2Authentication(org.orcid.core.oauth.OrcidOAuth2Authentication) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) HashSet(java.util.HashSet)

Example 8 with InvalidTokenException

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

the class OrcidClientCredentialEndPointDelegatorTest method generateRefreshTokenTest.

@Test
public void generateRefreshTokenTest() {
    //Generate the access token
    SecurityContextTestUtils.setUpSecurityContextForClientOnly(CLIENT_ID_1, ScopePathType.ACTIVITIES_UPDATE, ScopePathType.READ_LIMITED);
    OrcidOauth2AuthoriziationCodeDetail authCode = createAuthorizationCode("code-1", CLIENT_ID_1, "http://www.APP-5555555555555555.com/redirect/oauth", true, "/activities/update");
    MultivaluedMap<String, String> formParams = new MultivaluedMapImpl();
    formParams.add("client_id", CLIENT_ID_1);
    formParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
    formParams.add("grant_type", "authorization_code");
    formParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
    formParams.add("code", authCode.getId());
    Response response = orcidClientCredentialEndPointDelegator.obtainOauth2Token(null, formParams);
    assertNotNull(response);
    assertNotNull(response.getEntity());
    DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) response.getEntity();
    assertNotNull(token);
    assertTrue(!PojoUtil.isEmpty(token.getValue()));
    assertNotNull(token.getRefreshToken());
    assertTrue(!PojoUtil.isEmpty(token.getRefreshToken().getValue()));
    //Generate the refresh token
    MultivaluedMap<String, String> refreshTokenformParams = new MultivaluedMapImpl();
    refreshTokenformParams.add("client_id", CLIENT_ID_1);
    refreshTokenformParams.add("client_secret", "DhkFj5EI0qp6GsUKi55Vja+h+bsaKpBx");
    refreshTokenformParams.add("grant_type", "refresh_token");
    refreshTokenformParams.add("redirect_uri", "http://www.APP-5555555555555555.com/redirect/oauth");
    refreshTokenformParams.add("refresh_token", token.getRefreshToken().getValue());
    String authorization = "bearer " + token.getValue();
    Response refreshTokenResponse = orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
    assertNotNull(refreshTokenResponse);
    assertNotNull(refreshTokenResponse.getEntity());
    DefaultOAuth2AccessToken refreshToken = (DefaultOAuth2AccessToken) refreshTokenResponse.getEntity();
    assertNotNull(refreshToken);
    assertTrue(!PojoUtil.isEmpty(refreshToken.getValue()));
    assertNotNull(refreshToken.getRefreshToken());
    assertTrue(!PojoUtil.isEmpty(refreshToken.getRefreshToken().getValue()));
    //Assert that both tokens expires at the same time
    assertEquals(token.getExpiration(), refreshToken.getExpiration());
    //Try to generate another one, and fail, because parent token was disabled
    try {
        orcidClientCredentialEndPointDelegator.obtainOauth2Token(authorization, refreshTokenformParams);
    } catch (InvalidTokenException e) {
        assertTrue(e.getMessage().contains("Parent token is disabled"));
    }
}
Also used : Response(javax.ws.rs.core.Response) InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OrcidOauth2AuthoriziationCodeDetail(org.orcid.persistence.jpa.entities.OrcidOauth2AuthoriziationCodeDetail) MultivaluedMapImpl(com.sun.jersey.core.util.MultivaluedMapImpl) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test)

Example 9 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException 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 10 with InvalidTokenException

use of org.springframework.security.oauth2.common.exceptions.InvalidTokenException 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)

Aggregations

InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)21 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)8 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)6 Date (java.util.Date)4 Test (org.junit.Test)4 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)4 DBUnitTest (org.orcid.test.DBUnitTest)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)3 OAuth2AccessDeniedException (org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException)3 InvalidScopeException (org.springframework.security.oauth2.common.exceptions.InvalidScopeException)3 OAuth2Exception (org.springframework.security.oauth2.common.exceptions.OAuth2Exception)3 HashSet (java.util.HashSet)2 NoResultException (javax.persistence.NoResultException)2 OrcidOAuth2Authentication (org.orcid.core.oauth.OrcidOAuth2Authentication)2 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)2 Authentication (org.springframework.security.core.Authentication)2 Jwt (org.springframework.security.jwt.Jwt)2 JsonParser (com.fasterxml.jackson.core.JsonParser)1 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)1