Search in sources :

Example 1 with OAuth2Exception

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

the class DefaultTokenServicesWithInMemoryTests method testDifferentRefreshTokenMaintainsState.

@Test
public void testDifferentRefreshTokenMaintainsState() throws Exception {
    // create access token
    getTokenServices().setAccessTokenValiditySeconds(1);
    getTokenServices().setClientDetailsService(new ClientDetailsService() {

        public ClientDetails loadClientByClientId(String clientId) throws OAuth2Exception {
            BaseClientDetails client = new BaseClientDetails();
            client.setAccessTokenValiditySeconds(1);
            client.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "refresh_token"));
            return client;
        }
    });
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false, Collections.singleton("read")), new TestAuthentication("test2", false));
    DefaultOAuth2AccessToken firstAccessToken = (DefaultOAuth2AccessToken) getTokenServices().createAccessToken(expectedAuthentication);
    OAuth2RefreshToken expectedExpiringRefreshToken = firstAccessToken.getRefreshToken();
    // Make it expire (and rely on mutable state in volatile token store)
    firstAccessToken.setExpiration(new Date(System.currentTimeMillis() - 1000));
    // create another access token
    OAuth2AccessToken secondAccessToken = getTokenServices().createAccessToken(expectedAuthentication);
    assertFalse("The new access token should be different", firstAccessToken.getValue().equals(secondAccessToken.getValue()));
    assertEquals("The new access token should have the same refresh token", expectedExpiringRefreshToken.getValue(), secondAccessToken.getRefreshToken().getValue());
    // refresh access token with refresh token
    TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", Collections.singleton("read"), null);
    getTokenServices().refreshAccessToken(expectedExpiringRefreshToken.getValue(), tokenRequest);
    assertEquals(1, getAccessTokenCount());
}
Also used : BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) BaseClientDetails(org.springframework.security.oauth2.provider.client.BaseClientDetails) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ClientDetailsService(org.springframework.security.oauth2.provider.ClientDetailsService) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) Test(org.junit.Test)

Example 2 with OAuth2Exception

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

the class AbstractResourceOwnerPasswordProviderTests method testTokenEndpointWrongPassword.

@Test
@OAuth2ContextConfiguration(value = ResourceOwner.class, initialize = false)
public void testTokenEndpointWrongPassword() throws Exception {
    ResourceOwnerPasswordResourceDetails resource = (ResourceOwnerPasswordResourceDetails) context.getResource();
    resource.setPassword("bogus");
    try {
        new OAuth2RestTemplate(resource).getAccessToken();
    } catch (OAuth2AccessDeniedException e) {
        String summary = ((OAuth2Exception) e.getCause()).getSummary();
        assertTrue("Wrong summary: " + summary, summary.contains("Bad credentials"));
    }
}
Also used : ResourceOwnerPasswordResourceDetails(org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails) OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 3 with OAuth2Exception

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

the class WhitelabelErrorEndpoint method handleError.

@RequestMapping("/oauth/error")
public ModelAndView handleError(HttpServletRequest request) {
    Map<String, Object> model = new HashMap<String, Object>();
    Object error = request.getAttribute("error");
    // The error summary may contain malicious user input,
    // it needs to be escaped to prevent XSS
    String errorSummary;
    if (error instanceof OAuth2Exception) {
        OAuth2Exception oauthError = (OAuth2Exception) error;
        errorSummary = HtmlUtils.htmlEscape(oauthError.getSummary());
    } else {
        errorSummary = "Unknown error";
    }
    model.put("errorSummary", errorSummary);
    return new ModelAndView(new SpelView(ERROR), model);
}
Also used : HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with OAuth2Exception

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

the class DefaultWebResponseExceptionTranslator method translate.

public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
    // Try to extract a SpringSecurityException from the stacktrace
    Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);
    Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(OAuth2Exception.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception((OAuth2Exception) ase);
    }
    ase = (AuthenticationException) throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);
    if (ase != null) {
        return handleOAuth2Exception(new UnauthorizedException(e.getMessage(), e));
    }
    ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);
    if (ase instanceof AccessDeniedException) {
        return handleOAuth2Exception(new ForbiddenException(ase.getMessage(), ase));
    }
    ase = (HttpRequestMethodNotSupportedException) throwableAnalyzer.getFirstThrowableOfType(HttpRequestMethodNotSupportedException.class, causeChain);
    if (ase instanceof HttpRequestMethodNotSupportedException) {
        return handleOAuth2Exception(new MethodNotAllowed(ase.getMessage(), ase));
    }
    return handleOAuth2Exception(new ServerErrorException(e.getMessage(), e));
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) HttpRequestMethodNotSupportedException(org.springframework.web.HttpRequestMethodNotSupportedException) IOException(java.io.IOException) AuthenticationException(org.springframework.security.core.AuthenticationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 5 with OAuth2Exception

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

the class DefaultRedirectResolver method resolveRedirect.

public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception {
    Set<String> authorizedGrantTypes = client.getAuthorizedGrantTypes();
    if (authorizedGrantTypes.isEmpty()) {
        throw new InvalidGrantException("A client must have at least one authorized grant type.");
    }
    if (!containsRedirectGrantType(authorizedGrantTypes)) {
        throw new InvalidGrantException("A redirect_uri can only be used by implicit or authorization_code grant types.");
    }
    Set<String> redirectUris = client.getRegisteredRedirectUri();
    if (redirectUris != null && !redirectUris.isEmpty()) {
        return obtainMatchingRedirect(redirectUris, requestedRedirect);
    } else if (StringUtils.hasText(requestedRedirect)) {
        return requestedRedirect;
    } else {
        throw new InvalidRequestException("A redirect_uri must be supplied.");
    }
}
Also used : InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException)

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