Spring Security Using JWT in Spring Boot Application

We wanted to implement OAuth2 security using JWT to protect our API(s). We are running our micro-service application in kubernetes platform and using Active Directory as our Authorization Server.

High Level Flow

In our case the Authorization server is “Azure AD”. The resource server is our micro-service which exposes some API(s) which we want to protect. The client in our case is other applications and not a user. i.e. B2B.

Azure AD requires some changes to make it work as per OAuth2 compliance. you can follow this article on medium.com https://medium.com/@abhinavsonkar/making-azure-ad-oidc-compliant-5734b70c43ff to first setup your application in Azure AD and make in OAuth2 compliant.

Spring boot code change.

  1. You need below 3 dependencies in your project.


2. You need a SecurityConfiguration class which extends WebSecurityConfigurerAdapter. This class is where you would provide configuration such as which API(s) to protect and how to decode the JWT token.

The Spring security by default validates the “expiry” and “iss” for a token. in the above code we are additionally validating the “aud”.

3. We are using a separate class validate the JWT token and return the response accordingly by implementing OAuth2TokenValidator<Jwt>

4. You need to define 2 important URL’s as part of your application.properties

The values for these URL’s can be fetched from Azure AD portal. e.g.

Now, if you start your server and try to call your protected API path through any REST client like postman you should get 401 unless you send the JWT token.

After making these changes our swagger documentation broke because we were not able to launch that and other issues was how to test these protect API(s). Below code changes are required to your swagger code to make it work.

Reference Links

Senior Software Engineer — Samsclub.com

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