org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException Java Examples

The following examples show how to use org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException {


    logger.debug("Get access token");
    Map<String, String> request = new HashMap<>();
    request.put("userIdentifier", details.getClientId());
    request.put("userSecret", details.getClientSecret());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(details.getAccessTokenUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, details, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #2
Source File: SmartlingAuthorizationCodeAccessTokenProvider.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest accessTokenRequest) throws UserRedirectRequiredException {

    logger.debug("Get refresh token");

    SmartlingOAuth2ProtectedResourceDetails smartlingOAuth2ProtectedResourceDetails = (SmartlingOAuth2ProtectedResourceDetails) resource;
    Map<String, String> request = new HashMap<>();
    request.put("refreshToken", refreshToken.getValue());

    DefaultOAuth2AccessToken defaultOAuth2AccessToken = null;
    try {
        DateTime now = getNowForToken();
        AuthenticationResponse authenticationResponse = restTemplate.postForObject(smartlingOAuth2ProtectedResourceDetails.getRefreshUri(), request, AuthenticationResponse.class);
        defaultOAuth2AccessToken = getDefaultOAuth2AccessToken(now, authenticationResponse);
    } catch (Exception e) {
        String msg = "Can't get Smartling refresh token";
        logger.debug(msg, e);
        throw new OAuth2AccessDeniedException(msg, resource, e);
    }

    return defaultOAuth2AccessToken;
}
 
Example #3
Source File: OAuthClient.java    From cf-java-client-sap with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken createToken() {
    OAuth2ProtectedResourceDetails resource = getResourceDetails(credentials.getEmail(), credentials.getPassword(),
                                                                 credentials.getClientId(), credentials.getClientSecret());
    AccessTokenRequest request = createAccessTokenRequest(credentials.getEmail(), credentials.getPassword());

    ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
    try {
        return provider.obtainAccessToken(resource, request);
    } catch (OAuth2AccessDeniedException oauthEx) {
        HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
        throw new CloudOperationException(status, oauthEx.getMessage(), oauthEx.getSummary());
    }
}
 
Example #4
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails)details;
    System.out.println(request.getCurrentUri());
    if(request.getAuthorizationCode() == null) {
        if(request.getStateKey() == null) {
            throw this.getRedirectForAuthorization(resource, request);
        }

        this.obtainAuthorizationCode(resource, request);
    }
    System.out.println("code == " + request.getAuthorizationCode());
    return this.retrieveToken(request,
            resource, this.getParametersForTokenRequest(resource, request), this.getHeadersForTokenRequest(request));
}
 
Example #5
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken, AccessTokenRequest request) throws UserRedirectRequiredException, OAuth2AccessDeniedException {
    MultiValueMap<String, String> form = new LinkedMultiValueMap();
    form.add("grant_type", "refresh_token");
    form.add("refresh_token", refreshToken.getValue());
    form.add("appid", resource.getClientId());

    try {
        return this.retrieveToken(request, resource, form, this.getHeadersForTokenRequest(request));
    } catch (OAuth2AccessDeniedException var6) {
        throw this.getRedirectForAuthorization((AuthorizationCodeResourceDetails)resource, request);
    }
}
 
Example #6
Source File: MyAuthorizationCodeAccessTokenProvider.java    From springboot-security-wechat with Apache License 2.0 5 votes vote down vote up
protected OAuth2AccessToken retrieveToken(final AccessTokenRequest request,
                                          OAuth2ProtectedResourceDetails resource,
                                          MultiValueMap<String, String> form,
                                          HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        this.authenticationHandler.authenticateTokenRequest(resource, form, headers);
        this.tokenRequestEnhancer.enhance(request, resource, form, headers);
        final ResponseExtractor<OAuth2AccessToken> delegate = this.getResponseExtractor();

        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if(response.getHeaders().containsKey("Set-Cookie")) {
                    request.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }

                return (OAuth2AccessToken)delegate.extractData(response);
            }
        };
        System.out.println("URI == " + this.getAccessTokenUri(resource, form));
        return (OAuth2AccessToken)this.getRestTemplate().execute(this.getAccessTokenUri(resource, form),
                this.getHttpMethod(),
                this.getRequestCallback(resource, form, headers),
                extractor,
                form.toSingleValueMap());
    } catch (OAuth2Exception var8) {
        System.out.println(var8.toString());
        throw new OAuth2AccessDeniedException("Access token denied.", resource, var8);
    } catch (RestClientException var9) {
        System.out.println(var9.toString());
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, var9);
    }
}
 
Example #7
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("ROLE_ADMIN 角色测试")
void testAdminRoleSucceedAndTestRoleFailedWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("READ"));
    ResponseEntity<String> response = template.exchange(URL + "/admin", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("ADMIN", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/test", GET, null, String.class));
}
 
Example #8
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("ROLE_Test 角色测试")
void testTestRoleSucceedWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("test", "123456", Collections.singletonList("READ"));
    ResponseEntity<String> response = template.exchange(URL + "/test", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("TEST", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/admin", GET, null, String.class));
}
 
Example #9
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("SCOPE_READ 授权域测试")
void testScopeReadWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("READ"));
    ResponseEntity<String> response = template.exchange(URL + "/read", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("READ", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/write", GET, null, String.class));
}
 
Example #10
Source File: TestControllerTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
@DisplayName("SCOPE_WRITE 授权域测试")
void testScopeWriteWhenPassed() {
    OAuth2RestTemplate template = oauth2RestTemplate("admin", "123456", Collections.singletonList("WRITE"));
    ResponseEntity<String> response = template.exchange(URL + "/write", GET, null, String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
    assertEquals("WRITE", response.getBody());
    assertThrows(OAuth2AccessDeniedException.class,
        () -> template.exchange(URL + "/read", GET, null, String.class));
}
 
Example #11
Source File: OAuth2ConfigResourceClientTest.java    From spring-cloud-services-connector with Apache License 2.0 5 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
public void shouldBeDenied() {
	ConfigClientOAuth2ResourceDetails invalidCrendentialsResource = new ConfigClientOAuth2ResourceDetails();
	invalidCrendentialsResource.setClientId("wrongClient");
	invalidCrendentialsResource.setAccessTokenUri(resource.getAccessTokenUri());
	invalidCrendentialsResource.setClientSecret("wrongsecret");
	invalidCrendentialsResource.setScope(resource.getScope());
	invalidCrendentialsResource.setGrantType(resource.getGrantType());

	new ConfigResourceClientAutoConfiguration()
			.configResourceClient(invalidCrendentialsResource,
					configClientProperties)
			.getConfigFile("nginx.conf");
}
 
Example #12
Source File: OAuth2FeignRequestInterceptorTests.java    From spring-cloud-security with Apache License 2.0 5 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
public void tryToAcquireToken() {
	oAuth2FeignRequestInterceptor = new OAuth2FeignRequestInterceptor(
			new DefaultOAuth2ClientContext(),
			new BaseOAuth2ProtectedResourceDetails());
	OAuth2AccessToken oAuth2AccessToken = oAuth2FeignRequestInterceptor.getToken();
	Assert.assertTrue(oAuth2AccessToken.getValue() + " Must be null",
			oAuth2AccessToken.getValue() == null);
}
 
Example #13
Source File: GoogleFitShim.java    From shimmer with Apache License 2.0 5 votes vote down vote up
@Override
public OAuth2AccessToken refreshAccessToken(
        OAuth2ProtectedResourceDetails resource,
        OAuth2RefreshToken refreshToken, AccessTokenRequest request)
        throws UserRedirectRequiredException,
        OAuth2AccessDeniedException {

    OAuth2AccessToken accessToken = super.refreshAccessToken(resource, refreshToken, request);
    // Google does not replace refresh tokens, so we need to hold on to the existing refresh token...
    if (accessToken.getRefreshToken() == null) {
        ((DefaultOAuth2AccessToken) accessToken).setRefreshToken(refreshToken);
    }
    return accessToken;
}
 
Example #14
Source File: CustomConfigAuthorizationServerIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
public void givenOAuth2Context_whenAccessTokenIsRequestedWithInvalidException_ThenExceptionIsThrown() {
    ClientCredentialsResourceDetails resourceDetails = getClientCredentialsResourceDetails("baeldung", singletonList("write"));
    OAuth2RestTemplate restTemplate = getOAuth2RestTemplate(resourceDetails);

    restTemplate.getAccessToken();
}
 
Example #15
Source File: MyControllerIT.java    From resource-server-testing with MIT License 4 votes vote down vote up
@Test(expected = OAuth2AccessDeniedException.class)
@OAuth2ContextConfiguration(EveDetails.class)
public void testHelloEve() {
	restTemplate.getForEntity(host + "/hello", String.class);
}