Integrating Spring Cloud Gateway with OAuth2.0 for Unified Authentication and Authorization
This article demonstrates how to build a unified authentication and authorization solution by integrating Spring Cloud Gateway with OAuth2.0, covering architecture design, service setup, JWT token handling, custom authentication and authorization managers, Redis-based permission management, and end‑to‑end testing steps.
Microservice Authentication Schemes
Two typical approaches are discussed: (1) each microservice handles its own authentication and authorization, leading to tight coupling and maintenance overhead; (2) a unified gateway performs authentication and authorization, allowing services to focus on business logic.
Case Architecture
The article adopts the second approach, building a unified solution with Spring Cloud Gateway and Spring Cloud Security . Four roles are defined: client, gateway, OAuth2.0 authorization server, and a collection of microservices.
Authentication and Authorization Flow
Client requests a token from the gateway.
Gateway forwards the request to the authorization server.
Authorization server validates credentials and issues a JWT token.
Client uses the token to access resources via the gateway.
Gateway validates the token (signature, expiration) and checks permissions before forwarding to the target service.
Target service processes the request.
Service Construction
Three services are created:
Name
Function
oauth2-cloud-auth-server
OAuth2.0 authentication and authorization server
oauth2-cloud-gateway
API gateway
oauth2-cloud-order-service
Order resource service
Authentication Service Setup
A JwtTokenUserDetailsService class is added to load users from a simulated database (two users: user with ROLE_user and admin with ROLE_admin and ROLE_user ). The SecurityConfig class configures Spring Security to use this service.
Gateway Service Setup
Dependencies for OAuth2.0 are added, and JWT token configuration is aligned with the authentication server.
Custom Authentication Manager
A JwtAuthenticationManager implementing ReactiveAuthenticationManager parses the JWT, verifies its signature and expiration, and throws an exception if validation fails.
Custom Authorization Manager
A JwtAccessManager implementing ReactiveAuthorizationManager extracts permissions from the token and compares them with the permissions stored in Redis for the requested URI. Access is granted when there is an intersection.
Exception Handling
Custom handlers RequestAuthenticationEntryPoint (for invalid/expired tokens) and RequestAccessDeniedHandler (for insufficient permissions) are created to return tailored error responses via the gateway’s global exception mechanism.
OAuth2.0 Configuration
The SecurityConfig class is annotated with @EnableWebFluxSecurity (instead of @EnableWebSecurity ) because the gateway is built on WebFlux. It registers the authentication filter, authorization manager, exception handlers, whitelist, and CORS filter.
Global Filter for User Propagation
A global filter extracts user information from the JWT, encodes it as JSON, encrypts it with Base64, and injects it into request headers so downstream services can retrieve detailed user data.
Order Service Construction
The order service does not need its own Spring Security configuration; it simply decrypts the user data from the request header. Two endpoints are provided: /order/login/info (accessible by ROLE_user and ROLE_admin ) and /order/login/admin (requires ROLE_admin ).
Why Store URI‑Permission Mapping in Redis?
Storing permissions in Redis enables dynamic permission checks at the gateway level, simplifying permission updates without redeploying services.
Testing
All three services are started, a token is obtained using the password grant for user user , and the token is used to call the order service endpoints. The /order/login/info call succeeds, while the /order/login/admin call is blocked by the gateway due to insufficient permissions.
Conclusion
The article provides a complete, step‑by‑step guide to integrating Spring Cloud Gateway with OAuth2.0 for unified authentication and authorization, demonstrating custom managers, Redis‑based permission handling, and end‑to‑end testing, while noting that further refinements may be needed for production use.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.