Reputation: 786
I try to implement OAuth2 with Spring Security and I have studied the samples provided by Spring in the following Github: https://github.com/spring-projects/spring-security-oauth/blob/master/samples/oauth2/tonr/src/main/java/org/springframework/security/oauth/examples/config/WebMvcConfig.java
This OAuth2 sample is divided in two projects :
Tonr allows to show photos from Sparklr and also includes a Facebook API client to list friends of an account. It seems that once got from one provider, the same token is sent to all OAuth2 providers, even if the token doesn't come from the called provider.
Steps:
The sparklr token is sent to Facebook (visible in debug logs), and obviously Facebook returns a 400 Bad Request Error.
If now, I log out from tonr, click directly to Facebook friends page and log in tonr again, it is working; a token is asked to Facebook and access is granted. So the same OAuth2ClientContext and same token are kept from Sparklr to Facebook.
Question: How to separate OAuth2ClientContext to keep the token with its respective resource server?
I tried to instanciate a different OAuth2ClientContext bean for facebookRestTemplate, but the OAuth2 flow is broken with:
@Bean(name = "facebookClientContext")
public OAuth2ClientContext facebookClientContext() {
return new DefaultOAuth2ClientContext();
}
@Bean
public OAuth2RestTemplate facebookRestTemplate(@Qualifier("facebookClientContext") OAuth2ClientContext clientContext) {
...
Upvotes: 3
Views: 1027
Reputation: 106
I had the same problem. I solved it the same as you did except that you should:
See OAuth2ClientConfiguration as a guideline.
Modify your WebMvcConfig$ResourceConfiguration:
@Resource(name = "accessTokenRequest")
private AccessTokenRequest accessTokenRequest;
@Bean
@Qualifier("facebookClientContext")
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public DefaultOAuth2ClientContext facebookClientContext() {
return new DefaultOAuth2ClientContext(accessTokenRequest);
}
@Bean
public OAuth2RestTemplate facebookRestTemplate(
@Qualifier("facebookClientContext") OAuth2ClientContext clientContext) {
OAuth2RestTemplate template = new OAuth2RestTemplate(facebook(), clientContext);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(
Arrays.asList(MediaType.APPLICATION_JSON, MediaType.valueOf("text/javascript")));
template.setMessageConverters(Arrays.<HttpMessageConverter<?>>asList(converter));
return template;
}
@Bean
public OAuth2RestTemplate sparklrRestTemplate(
@Qualifier("oauth2ClientContext") OAuth2ClientContext clientContext) {
return new OAuth2RestTemplate(sparklr(), clientContext);
}
@Bean
public OAuth2RestTemplate sparklrRedirectRestTemplate(
@Qualifier("oauth2ClientContext") OAuth2ClientContext clientContext) {
return new OAuth2RestTemplate(sparklrRedirect(), clientContext);
}
Upvotes: 2