Spring Oauth2 Client Credential Flow Example

I am trying to embed a service security service in spring boot services using spring oauth2. I want the service to access the protected resource of another service without any user involvement.

There are many examples for the type of authorization code resolution, but not very many for the type of client credential that seems to be the right one for this use case.

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

How can I use the client credential type in a java client using RestTemplate and spring oauth2?

I would think that this should be as simple as adding a dependency, annotation, and configuration file, but I can't get it to work.

+5
source share
1 answer

It's simple.

  • Create whitch config class annotated with @Configutration
  • In this class, create a Bean of OAuth2ProtectedResourceDetails type (interface) and create a ClientCredentialsResourceDetails object in this method. Add your values ​​to it and return them.
  • Create a second Bean of type OAuth2RestTemplate in the configuration class and create a DefaultOAuth2ClientContext object with a standard constructor in this method. Then create an OAuth2RestTemplate and add the OAuth2ProtectedResourceDetails Bean and DefaultOAuth2ClientContext to it. Then return the OAuth2RestTemplate object.
  • Add it with @Autowired in your controller and service classes to use it.
0
source

Source: https://habr.com/ru/post/1236651/


All Articles