Spring Cloud OpenFeign OAuth 2.0 Client Credentials Non-interactive S2S Authentication With Spring Security 5

In the world of microservices, we often come across scenarios of service to service (S2S) communication that require service to establish their authenticity for successful dialogue exchange. Here I will walk you through the simple steps of establishing OAuth2 authenticity for consumer service, using the Spring Security 5 framework, to be able to talk to supplier service.

For brevity, let’s get to the point:

Step 1) Include the dependencies:

Step 2) Spring configuration:

Step 3) Application Code:

Spring expects OAuth2AuthorizedClientManager bean type in context, giving you the flexibility to define the custom implementations. But we will go with the very basic spring provided out of box in-memory token management, which fits most of the use cases.

OAuth2Provider service will be responsible to provide a valid authentication token whenever asked for the given AuthZ server. It internally delegates the request to OAuth2AuthorizedClientManager.

Next, we will be injecting the token in every outbound HTTP request through request interceptor using feign configuration.

NOTE: Last but not least, if your consumer app exposes some web controllers say even spring actuator endpoints (health, info, etc), you will have to configure/app WebSecurity for whitelisting. For brevity, I am whitelisting all endpoints here but you may have a different use case.

Voila! job done. With minimal code, you enabled this consumer app to be able to talk to supplier service secured by OAuth2.

Benefits of using Spring Security 5 OAuth2 client wrapper:

a) More pragmatic than programmatic, reduces the boilerplate code to configuration.
b) Gives you all features of OAuth2 for Service to Service (S2S) authentication, right out of the box with no explicit code:

  • Authentication
  • Authorization
  • Token Cache
  • Token Refresh
  • Concurrency

I hope you liked ❤️ this article, stay tuned for more posts. All feedback, comments & questions are welcomed. 🏳️‍🌈


If this helped you reduce time to develop, you can buy me a cup of coffee ☕

Lead Full Stack & DevOps Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store