Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Oauth2 client credentials flow example

I am trying to implement service to service security into spring boot services using spring oauth2. I want a service to access a secured resource of another service without any user action involved.

There are a lot of examples for authorization code grant type, but not very much about the client credentials grant type, which seems to be the right one for this use case.

I can set up the auth server and use a curl request to get a token. The tests I found used Http Objects to check status codes.

How can I use the client credentials grant type in a java client with RestTemplate and spring oauth2?

I would think it must be as simple as adding a dependency, an annotation and a config file, yet I can't make it run.

like image 667
Tom Saenger Avatar asked Nov 09 '22 01:11

Tom Saenger


1 Answers

It's quite simple:

  1. Create a Config class which is annotated with @Configuration.
  2. In this class, create an instance implementing the interface OAuth2ProtectedResourceDetails and create a ClientCredentialsResourceDetails instance in that method. Add your values to it and return it.
  3. Create a second instance of type OAuth2RestTemplate in the Configuration class and create in that method a DefaultOAuth2ClientContext instance by calling the default constructor. Then create an OAuth2RestTemplate and add the OAuth2ProtectedResourceDetails instance and the DefaultOAuth2ClientContext instance to it. Subsequently return the OAuth2RestTemplate instance.
  4. Add it with @Autowired in both your Controller and Service instances to use it.
like image 163
Rocks360 Avatar answered Nov 15 '22 07:11

Rocks360