Member-only story
JWT Authentication With Spring Boot’s Inbuilt OAuth2 Resource Server
Using Spring Boot’s inbuilt OAuth2 Resource Server with security best practices for JWT based authentication

TL;DR
This article proposes a better approach to achieve JWT authentication for your SPA web application backend REST APIs using Spring Boot’s inbuilt OAuth2 Resource Server. In summary, the proposed approach is:
- More Secure — Use an RSA private key instead of a single secret token (symmetric key) to sign JWTs and RSA public key for signature verification.
- Convenient — An endpoint (“/login”) to obtain a signed JWT in exchange for valid user credentials.
- Authorization — Spring Security’s method security can be used since the JWT information is available as Authentication at controller level; Can use “@PreAuthorize”, “@PostAuthorize” annotations with SPEL for complex authorization needs.
- Extendable — Can be extended to support federated authentication (ex: “Login with Google”, etc.) and to support refresh_tokens and client side JWT validation using “/jwt” endpoint.
- Best Practices — Use Spring Boot’s inbuilt OAuth2 Resource Server for inbound request authentication with JWT.
- Scalable — This approach is stateless and JWT authentication can be scaled horizontally as desired.
Source Code:
Update (2021/08/06): A sample ReactJs app to consume this springboot service has been added under https://github.com/IMS94/spring-boot-jwt-authentication/tree/master/frontend in the github repository.
Update (2021/09/27): I have published a new article on how to extend this approach to introduce RBAC (Role Based Access Control) on top of JWT authentication: https://medium.com/geekculture/role-based-access-control-rbac-with-spring-boot-and-jwt-bc20a8c51c15