Authentication is required to obtain an access token - when using 'password' grant and Spring's ResourceOwnerPasswordResourceDetails - spring

I am new to Spring Security and I want to implement a client for a OAUTH2 secured service that only accepts password grant.
Obtaining the access_token from the auth server is done using data in the http body like this:
client_id={{clientId}}&client_secret={{client_secret}}&grant_type=password&username={{username}}&password={{password}}
Afterwards the access_token must be used in the header field Authorization to access the actual service. (e.g. Authorization=Bearer <access_token>)
My goal is to use the provided features from Spring Security OAuth2 to request an access_token from the auth service, and use it for accessing the service endpoints until token expiration. I also like to have that my access_token is automatically refreshed using the refresh_token value from the auth server. I want to achieve this while fully utilizing Spring's features.
I found that I can use OAuth2RestTemplate with ResourceOwnerPasswordResourceDetails for the grant_type password.
The StackOverflow post oAuth2 client with password grant in Spring Security was very helpful for me, but I have not got it to work.
I also found the post Authentication is required to obtain an access token (anonymous not allowed) where a user encountered the same exception, but uses client_credentials and AuthorizationCodeResourceDetails.
At the moment my code looks like this.
#Service
public class MyClient {
#Autowired
private OAuth2RestTemplate restTemplate;
#Value("${authServer.accessTokenUri}")
private String accessTokenUri;
#Value("${authServer.clientId}")
private String clientId;
#Value("${authServer.clientSecret}")
private String clientSecret;
#Value("${authServer.username}")
private String username;
#Value("${authServer.password}")
private String password;
#Value("${serviceUrl}")
private String serviceUrl;
#Bean
public OAuth2RestTemplate restTemplate(OAuth2ClientContext oauth2ClientContext) {
OAuth2RestTemplate template = new OAuth2RestTemplate(resource(), oauth2ClientContext);
template.setAccessTokenProvider(accessTokenProvider());
return template;
}
#Bean
public AccessTokenProvider accessTokenProvider() {
ResourceOwnerPasswordAccessTokenProvider tokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
return new AccessTokenProviderChain(
Arrays.<AccessTokenProvider>asList(tokenProvider)
);
}
#Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setId(clientId);
resource.setAccessTokenUri(accessTokenUri);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setGrantType("password");
resource.setClientAuthenticationScheme(AuthenticationScheme.form); // fetch access_token by sending authentication data in HTTP Body
resource.setAuthenticationScheme(AuthenticationScheme.header); // send access_token via HTTP Header 'Bearer' field when accessing actual service
resource.setUsername(username);
resource.setPassword(password);
return resource;
}
public void getDataFromService() {
String response = restTemplate.getForObject(serviceUrl, String.class);
}
}
An exception is thrown in AccessTokenProviderChain, because of this block.
if (auth instanceof AnonymousAuthenticationToken) {
if (!resource.isClientOnly()) {
throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
}
}
Here is the exception stack trace.
org.springframework.security.authentication.InsufficientAuthenticationException: Authentication is required to obtain an access token (anonymous not allowed)
at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:91) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:221) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:173) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:105) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:731) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128) ~[spring-security-oauth2-2.3.4.RELEASE.jar:na]
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:670) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:311) ~[spring-web-5.1.7.RELEASE.jar:5.1.7.RELEASE]
As you can see I cannot request an access_token. I do not understand why I get this exception, because if I directly request an access_token from the auth server using the curl command, I am able to authenticate using only the provided data as stated.
I manually obtained an access_token successfully like this, when adding the following code before invoking restTemplate.getForObject(...).
ResourceOwnerPasswordAccessTokenProvider accessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
OAuth2AccessToken token = accessTokenProvider.obtainAccessToken(resource(), new DefaultAccessTokenRequest());
restTemplate.getOAuth2ClientContext().setAccessToken(token);
String token = restTemplate.getAccessToken();
But, manually obtaining the access_token is not that what I want. Is there something I am missing? Is it possible to automatically obtain an access_token and refresh it using Spring Security with password grant?
Although checking code multiple hours on Github, StackOverflow etc. ... I have not been able to get my code to work.
UPDATE:
I found that my ResourceOwnerPasswordResourceDetails instance inside my OAuth2RestTemplate instance is not initialized, when I want to make use of it inside getDataFromService(). (i.e. the fields like username are null). After clarification and help from #JoeGrandja, my question now does not really target Spring Security, but rather Spring.
What can I do to make use of the #Value annotations inside a #Bean annotated method. At the moment, when the restTemplate is constructed using the #Bean annotated method resource(), the values from the application.yml are obviously not available yet.

I found a solution with the help and support of #JoeGrandja. Thank you very much! :)
If anyone else has problems, here is my working solution. I also recommend reading the comments from #JoeGrandja above.
#Configuration
#ConfigurationProperties(prefix = "authserver")
public class AuthServerConfigProperties {
private String accessTokenUri;
private String clientId;
private String grantType;
private String clientSecret;
private String username;
private String password;
// Getter & Setter for all properties ...
}
#Configuration
public class CommConfig {
#Autowired
AuthServerConfigProperties configProperties;
#Bean
public OAuth2RestOperations restTemplate(OAuth2ClientContext oauth2ClientContext) {
OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource(), oauth2ClientContext);
oAuth2RestTemplate.setAccessTokenProvider(new ResourceOwnerPasswordAccessTokenProvider());
return oAuth2RestTemplate;
}
#Bean
protected OAuth2ProtectedResourceDetails resource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setId(configProperties.getClientId()); // not necessary
resource.setAccessTokenUri(configProperties.getAccessTokenUri());
resource.setClientId(configProperties.getClientId());
resource.setClientSecret(configProperties.getClientSecret());
resource.setGrantType(configProperties.getGrantType());
resource.setClientAuthenticationScheme(AuthenticationScheme.form); // fetch access_token by sending authentication data in HTTP Body
resource.setAuthenticationScheme(AuthenticationScheme.header); // send access_token via HTTP Header 'Bearer' field when accessing actual service
resource.setUsername(configProperties.getUsername());
resource.setPassword(configProperties.getPassword());
return resource;
}
}
#RestController
public class MyController {
#Autowired
private OAuth2RestOperations restTemplate;
#Value("${serviceUrl}")
private String serviceUrl;
#RequestMapping(value = "/getData", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<String> getData() {
String response = restTemplate.getForObject(serviceUrl, String.class);
return new ResponseEntity(response, HttpStatus.OK);
}
}

I had a similar problem: rest request was anonymous, but internal processing required oauth2 authorization, resolved with a simple extend:
public class CustomResourceOwnerPasswordResourceDetails extends ResourceOwnerPasswordResourceDetails {
#Override
public boolean isClientOnly() {
return true;
}
}

Related

Resolving OAuth2AuthorizedClient as a Spring bean

I have a controller that is autowired with many services. These services are HTTP restful calls that retrieve data from various data sources, but these services are protected with OAuth2.0.
I am trying to use Spring Security to implement a client-credentials flow that will allow these services to securely retrieve data from these protected data sources, but am having some difficulty in resolving the OAuth2AuthorizedClient data object at the service layer.
I've been trying to resolve the authorized client via the #RegisteredOAuth2AuthorizedClient annotation:
public void setAuthorizedClient(
#RegisteredOAuth2AuthorizedClient("azure") OAuth2AuthorizedClient authorizedClient) {
ClientRegistration clientRegistration =
this.clientRegistrationRepository.findByRegistrationId("azure");
System.out.println(clientRegistration);
OAuth2AccessToken accessToken = authorizedClient.getAccessToken();
jwtToken = accessToken.getTokenValue();
}
Is it possible to resolve the OAuth2AuthorizedClient as a Spring bean that can then be injected into another bean?
Or is there a better way of architecting such a system?
Thanks!
Bit of an old question but I just solved this for myself so here goes:
You can create a #Component that returns the OAuth2AuthorizedClient for you, and inject that where you need it. Here is an example approach:
Create a provider Component class
Inject the readily available OAuth2AuthorizedClientService bean to your class
Create a method that uses the service in order to return the OAuth2AuthorizedClient
Inject your provider class to your Controller
Example:
#Component
public class OAuth2AuthorizedClientProvider {
#Autowired
private OAuth2AuthorizedClientService clientService;
public OAuth2AuthorizedClient getClient() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
return clientService.loadAuthorizedClient(oauthToken.getAuthorizedClientRegistrationId(), oauthToken.getName());
}
and then OAuth2AuthorizedClientProvider is used in a controller like so:
#RestController
public class Endpoint {
#Autowired
private final OAuth2AuthorizedClientProvider oauth2AuthorizedClientProvider;
#GetMapping("/mymethod")
public String mymethod() {
return oauth2AuthorizedClientProvider.getClient().getAccessToken();
}
}

Getting UserInfo information from a JWT token and using only JWK validation on Spring Boot OAuth2 autoconfiguration

I'm creating a RESTful service that authenticates all incoming requests using the OAuth2 mechanism with an external Keycloak User Authentication Server (UAA).
The service acts as a Resource Server using the #EnableResourceServer with the following configuration:
#Configuration
#EnableResourceServer
#Order(0)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final ResourceServerTokenServices resourceServerTokenServices;
#Autowired
public SecurityConfig(ResourceServerTokenServices resourceServerTokenServices) {
this.resourceServerTokenServices = resourceServerTokenServices;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.anyRequest().authenticated().and().addFilterAfter(oAuth2AuthenticationProcessingFilter(), AbstractPreAuthenticatedProcessingFilter.class);
}
private OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter() {
OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter = new OAuth2AuthenticationProcessingFilter();
oAuth2AuthenticationProcessingFilter.setAuthenticationManager(oauthAuthenticationManager());
oAuth2AuthenticationProcessingFilter.setStateless(false);
return oAuth2AuthenticationProcessingFilter;
}
private AuthenticationManager oauthAuthenticationManager() {
OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager();
oAuth2AuthenticationManager.setResourceId("country-microservice");
oAuth2AuthenticationManager.setTokenServices(resourceServerTokenServices);
oAuth2AuthenticationManager.setClientDetailsService(null);
return oAuth2AuthenticationManager;
}
}
I'm also using the following dependencies to include the Spring Security OAuth2:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
</dependencies>
The users authenticate themselves on the UAA to obtain a JWT token that they must use to call the service that I'm creating. The JWT token itself contains the user information:
{
...
"realm_access": {
"roles": [
"user"
]
},
"scope": "profile email",
"email_verified": true,
"name": "Test Derp",
"preferred_username": "user1",
"given_name": "Test",
"family_name": "Derp",
"email": "test#test.com"
}
To avoid making another request to the UAA, the service uses the JWK to validate the incoming token. I'm setting the security.oauth2.resource.jwk.key-set-uri property using the Keycloak's Certificate Endpoint:
security.oauth2.resource.jwk.key-set-uri=http://localhost:9080/auth/realms/dev/protocol/openid-connect/certs
The problem is that Spring is not getting the user information that is found on the JWT token and fill it in the Authentication object.
I have the following controller to return the principal information:
#RestController
#RequestMapping(path = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
#GetMapping
public Object getUser(Authentication authentication) {
if (authentication != null) {
return authentication.getPrincipal();
}
return null;
}
}
The Authentication object is passed with null in the getUser function (with the JWK validation).
I've tried to use the following configuration to customize the JWKTokenStore with a JWTAccessTokenConverter, but it didn't work:
#Configuration
public class JwkStoreConfig {
private final ResourceServerProperties resource;
#Autowired
public JwkStoreConfig(ResourceServerProperties resource) {
this.resource = resource;
}
#Bean
#Primary
public JwtAccessTokenConverter accessTokenConverter() {
return new JwtAccessTokenConverter();
}
#Bean
public DefaultTokenServices jwkTokenServices(TokenStore jwkTokenStore) {
DefaultTokenServices services = new DefaultTokenServices();
services.setTokenStore(jwkTokenStore);
return services;
}
#Bean
public TokenStore jwkTokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
JwkTokenStore jwkTokenStore = new JwkTokenStore(this.resource.getJwk().getKeySetUri(), jwtAccessTokenConverter);
return jwkTokenStore;
}
}
The only solution that worked until now is to forget the usage of JWK and change the service to use the Keycloak's UserInfo to validate the incoming token, using the security.oauth2.resource.user-info-uri property and delete JWK URI property:
security.oauth2.resource.user-info-uri=http://localhost:9080/auth/realms/dev/protocol/openid-connect/userinfo
With this property set, the Authentication object is passed to the controller with the user information, but this makes the service to request the UAA everytime it needs to validate the incoming tokens.
Any ideas?
Thank you.
Regards.
The documentation for this is here, although to me it's not entirely clear and at least with my setup it doesn't work as it expected.
My understanding is that these two properties should be used together:
security.oauth2.resource.jwt.key-uri: http://localhost:9191/auth/realms/master
security.oauth2.resource.jwk.key-set-uri: http://localhost:9191/auth/realms/master/protocol/openid-connect/certs
That fails for me though, with a somewhat uninformative log message:
Authentication request failed: error="invalid_token", error_description="Cannot convert access token to JSON"
Debugging into Spring Security code a bit, it looks like if for what ever reason it could not internally resolve/create the public key for verifying the signature, it will give the error above.
This worked for me...
If you set the property security.oauth2.resource.jwt.key-value to the actual public key then it does verify, as well as unpack the user info from the JWT, without needing to call back to(or configure) the user info endpoint. The down side to that is the public key has to be copied into code and updated everywhere if it changes.
Note the value of this property has to include -----BEGIN PUBLIC KEY-----\n at the start and \n-----END PUBLIC KEY-----.
E.g.
security.oauth2.resource.jwt.key-value: "-----BEGIN PUBLIC KEY-----\nMIIB......\n-----END PUBLIC KEY-----"
I haven't tried, but I'm pretty sure that would also work with actual line breaks in YAML with:
security.oauth2.resource.jwt.key-value: |
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
I think the reason why the fist set of properties don't work for my set up is because the key returned from the key-uri doesn't have these begin and end segments and Spring Security expects them to be there.
This probably doesn't answer your question directly, but hopefully still helpful. Spring security logging was quite sparse, and I found those properties to be really fiddly in how much they changed the behavior of things without useful much logging info indicating what's going on, even on TRACE level.

How to add CORS headers to the Spring error page rendered by BasicErrorController?

I have a single page client being served by a Spring Boot REST MVC API application (spring boot version 1.5.2).
My app is secured via Auth0 JWT tokens. When things are working, the CORS headers for responses are provided by a ServletFilter that gets configured as part of setting up the security:
protected void configure(HttpSecurity http) throws Exception {
...
http.addFilterBefore(simpleCORSFilter(), Auth0AuthenticationFilter.class);
...
}
This seems to work everywhere I've tested it so far - but one place where it's not working is with the default Spring error page (path "/error", rendered by default by the BasicErrorController class).
When there's an exception thrown in my service methods, the error page works and renders the content I want as JSON in the response body, but the client app can't access the http response body because the response lacks CORS headers.
So the question: "how do I add CORS headers to the error page"?
Should I be removing the CORS filter from my security setup and applying the CORS filter more globally? Where would that be done - I can't find anything relevant in the Spring doccumentation.
Or should I be writing a custom Error controller? The only example of a custom error controller in the documentation just seems to allow you to return a string.
You can define a separate Controller for Error and allow cross origin to it using
#CrossOrigin("*")
Combining Poorvi's answer with Joni Karppinen's custom error controller code gives:
#RestController
public class ErrorController
implements org.springframework.boot.autoconfigure.web.ErrorController
{
private static final String PATH = "/error";
#Autowired private ErrorAttributes errorAttributes;
#Override
public String getErrorPath(){
return PATH;
}
// I guess when time comes to lock down cors header, we could use a spring
// value configuration here to share with corsfilter.
#CrossOrigin("*")
#RequestMapping(value = PATH, produces = "application/json")
public #ResponseBody
ErrorJson error(HttpServletRequest request, HttpServletResponse response){
return new ErrorJson(
response.getStatus(),
getErrorAttributes(request, false) );
}
private Map<String, Object> getErrorAttributes(
HttpServletRequest request,
boolean includeStackTrace
){
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
return errorAttributes.getErrorAttributes(
requestAttributes,
includeStackTrace);
}
}
class ErrorJson {
public Integer status;
public String error;
public String message;
public String timeStamp;
public String trace;
public ErrorJson(int status, Map<String, Object> errorAttributes){
this.status = status;
this.error = (String) errorAttributes.get("error");
this.message = (String) errorAttributes.get("message");
this.timeStamp = errorAttributes.get("timestamp").toString();
this.trace = (String) errorAttributes.get("trace");
}
}
Which seems to do the job for me.

Consume an OAuth-secured REST webservice using Spring oauth2

I want to consume a REST webservice from a server which protects his resources using oauth2.
I use Spring boot (JHipster).
To do this i have in SecurityConfiguration class this :
#Value("${oauth.resource:http://sercverUsingOAuth2}")
private String baseUrl;
#Value("${oauth.authorize:http://sercverUsingOAuth2/rest/oauth/token}")
private String authorizeUrl;
#Value("${oauth.token:http://sercverUsingOAuth2/rest/oauth/token}")
private String tokenUrl;
#Bean
public OAuth2RestOperations oauth2RestTemplate() {
AccessTokenRequest atr = new DefaultAccessTokenRequest();
return new OAuth2RestTemplate(resource(),
new DefaultOAuth2ClientContext(atr));
}
#Bean
protected OAuth2ProtectedResourceDetails resource() {
AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
resource.setAccessTokenUri(tokenUrl);
resource.setUserAuthorizationUri(authorizeUrl);
resource.setClientId("client_id");
resource.setClientSecret("client_secret");
resource.setGrantType("grant_type");
return resource;
}
This class (SecurityConfiguration) is annoted using :
#Configuration
#EnableWebSecurity
#EnableOAuth2Client
And this is my controller (Spring MVC) :
#RestController
#RequestMapping("/consume")
public class MyContrtoller {
#Inject
private OAuth2RestOperations oauth2RestTemplate;
#RequestMapping(value = "/oauth2", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<DataModel> getProducts() {
ResponseEntity<MyModel> forEntity = oauth2RestTemplate
.getForEntity("http://sercverUsingOAuth2/rest/resourceToConsume",
MyModel.class);
return forEntity.getBody().getData();
}
}
However when i want to consume my webservice (http://myHost/consume/oauth2) i get this Exception :
org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException:
Unable to obtain a new access token for resource 'null'. The provider manager
is not configured to support it.
I have googled and i found this :
github
stackoverflow
But it doesn't help me.
Thanks.
You are using the same URL for the authorization url and the token url. That was my first clue, then I saw your comments.
Even though you are changing the grant type, you are still using "AuthorizationCodeResourceDetails" when you should be using "ClientCredentialsResourceDetails" instead. This type of ResourceDetails is meant to be used for the case you are explaining.
ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
resource.setAccessTokenUri(TOKEN_URL);
resource.setClientId(CLIENT_ID);
resource.setClientSecret(CLIENT_SECRET);
resource.setClientAuthenticationScheme(AuthenticationScheme.form); //This line isn't always needed
return resource;

How to overwrite Spring Cloud OAuth2 client autoconfiguration?

We want to setup a microservice which provides a REST API so it is configured as a OAuth2 resource server. This service should also act as a OAuth2 client with the client credential grant. Here is the configuration:
spring.oauth2.client.id=clientCredentialsResource
spring.oauth2.client.accessTokenUri=http://localhost:9003/oauth/token
spring.oauth2.client.userAuthorizationUri=http://localhost:9003/oauth/authorize
spring.oauth2.client.grantType=client_credentials
spring.oauth2.client.clientId=<service-id>
spring.oauth2.client.clientSecret=<service-pw>
The resource server part works fine. For the client part we want to use Feign, Ribbon and Eureka:
#FeignClient("user")
public interface UserClient
{
#RequestMapping( method = RequestMethod.GET, value = "/user/{uid}")
Map<String, String> getUser(#PathVariable("uid") String uid);
}
Based on the gist in issue https://github.com/spring-cloud/spring-cloud-security/issues/56 I created a feign request intercepter which sets the access token from the autowired OAuth2RestOperations template in the feign request header
#Autowired
private OAuth2RestOperations restTemplate;
template.header(headerName, String.format("%s %s", tokenTypeName, restTemplate.getAccessToken().toString()));
But this gives me the error on calling the user service:
error="access_denied", error_description="Unable to obtain a new access token for resource 'clientCredentialsResource'. The provider manager is not configured to support it.
As I can see the OAuth2ClientAutoConfiguration creates always an instance of AuthorizationCodeResourceDetails for an web application but not the required ClientCredentialsResourceDetails which is only used for non-web applications. In the end the no access token privider is responsible for the resource details and the call failed in
AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:146)
I tried to overwrite the auto configuration but failed. Can somebody please give me a hint how to do it?
To switch off this piece of autoconfiguration you can set spring.oauth2.client.clientId= (empty), (per the source code), otherwise you have to "exclude" it in the #EnableAutoConfiguration. If you do that you can just set up your own OAuth2RestTemplate and fill in the "real" client ID from your own configuration, e.g.
#Configuration
#EnableOAuth2Client
public class MyConfiguration {
#Value("myClientId")
String myClientId;
#Bean
#ConfigurationProperties("spring.oauth2.client")
#Primary
public ClientCredentialsResourceDetails oauth2RemoteResource() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
details.setClientId(myClientId);
return details;
}
#Bean
public OAuth2ClientContext oauth2ClientContext() {
return new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
}
#Bean
#Primary
public OAuth2RestTemplate oauth2RestTemplate(
OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
OAuth2RestTemplate template = new OAuth2RestTemplate(details,
oauth2ClientContext);
return template;
}
}

Resources