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.

Background

Recently I wanted to implement a backend REST API using Spring Boot for an SPA (single page app) written in ReactJS. I could simply use session based authentication (stateful), but it would introduce a new set of requirements like _sharing session data across backend servers (without sticky sessions) _and _session aware load balancing (sticky sessions) _when scaling horizontally. Either way, the backend will be handling the burden of maintaining each user’s session data (aka. state). Therefore, I decided to go with stateless authentication.

#jwt #rest-api #authentication #spring-security #spring-boot

JWT Authentication with Spring Boot’s Inbuilt OAuth2 Resource Server
16.50 GEEK