5
votes

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.

1
Please update your question to add the code you tried and the errors you get. To improve your question please read How to ask stackoverflow.com/help/how-to-ask And How to create a Minimal, Complete, and Verifiable example stackoverflow.com/help/mcve. And never ask for tutorial/working example as we are not here to teach/do your work for youdavejal

1 Answers

1
votes

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.