In the microservice architecture, Spring Cloud Gateway, as the gateway layer, assumes important responsibilities such as request forwarding and permission verification. By integrating Spring Security and JWT (JSON Web Token), centralized permission authentication can be implemented at the gateway layer to ensure system security and data protection. The following are the detailed implementation steps:
1. Add dependencies
In the Spring Boot project, add Spring Cloud Gateway, Spring Security, and JWT related dependencies. The following isConfiguration example:
<dependencies> <!-- Spring Cloud Gateway --> <dependency> <groupId></groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- Spring Security --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- JWT Support --> <dependency> <groupId></groupId> <artifactId>jjwt-api</artifactId> <version>0.11.5</version> </dependency> <dependency> <groupId></groupId> <artifactId>jjwt-impl</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> <dependency> <groupId></groupId> <artifactId>jjwt-jackson</artifactId> <version>0.11.5</version> <scope>runtime</scope> </dependency> </dependencies>
2. Configure Spring Security
In Spring Cloud Gateway, use Spring Security's WebFlux module to implement permission verification. Here is a typical configuration class:
@Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, JwtAuthenticationManager jwtAuthenticationManager) { http .csrf().disable() // Disable CSRF protection .authorizeExchange(exchanges -> exchanges .pathMatchers("/login", "/register").permitAll() // Public login and registration interface .anyExchange().authenticated()) // Other requests require authentication .addFilterAt(jwtAuthenticationFilter(jwtAuthenticationManager), ); return (); } private AuthenticationWebFilter jwtAuthenticationFilter(JwtAuthenticationManager jwtAuthenticationManager) { AuthenticationWebFilter filter = new AuthenticationWebFilter(jwtAuthenticationManager); (new BearerTokenServerAuthenticationConverter()); return filter; } }
3. Implement JWT tool class
The JWT tool class is used to generate and parse JWT tokens. The following is the implementation of the tool class:
@Component public class JwtUtil { private String secret = "yourSecretKey"; // The key should be stored in a safe place to avoid hard code public Mono<String> extractUsername(String token) { return (extractClaim(token, Claims::getSubject)); } public Date extractExpiration(String token) { return extractClaim(token, Claims::getExpiration); } public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { final Claims claims = extractAllClaims(token); return (claims); } private Claims extractAllClaims(String token) { return ().setSigningKey(secret).parseClaimsJws(token).getBody(); } public Mono<String> generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return (createToken(claims, ())); } private String createToken(Map<String, Object> claims, String subject) { return () .setClaims(claims) .setSubject(subject) .setIssuedAt(new Date(())) .setExpiration(new Date(() + 1000 * 60 * 60 * 10)) // 10 hours expire .signWith(SignatureAlgorithm.HS256, secret) .compact(); } public Mono<Boolean> validateToken(String token, UserDetails userDetails) { final String username = extractUsername(token).block(); return ((()) && !isTokenExpired(token)); } private Boolean isTokenExpired(String token) { return extractExpiration(token).before(new Date()); } }
4. Implement the JWT authentication manager
JWT Authentication Manager is used to handle JWT's verification logic:
@Component public class JwtAuthenticationManager implements ReactiveAuthenticationManager { private final JwtUtil jwtUtil; private final UserDetailsService userDetailsService; public JwtAuthenticationManager(JwtUtil jwtUtil, UserDetailsService userDetailsService) { = jwtUtil; = userDetailsService; } @Override public Mono<Authentication> authenticate(Authentication authentication) { String token = (String) (); return (token) .flatMap(username -> { if ((token, (username)).block()) { UserDetails userDetails = (username); return (new UsernamePasswordAuthenticationToken(userDetails, token, ())); } else { return (); } }); } }
5. Implement Bearer Token Converter
The Bearer Token converter is used to extract JWT tokens from request headers:
public class BearerTokenServerAuthenticationConverter implements ServerAuthenticationConverter { @Override public Mono<Authentication> convert(ServerWebExchange exchange) { String authHeader = ().getHeaders().getFirst("Authorization"); if (authHeader != null && ("Bearer ")) { String token = (7); return (new BearerTokenAuthentication(token)); } return (); } }
6. Configure Gateway routing
existConfigure routing rules in the file:
spring: cloud: gateway: routes: - id: user-service uri: lb://USER-SERVICE predicates: - Path=/users/** filters: - JwtAuthenticationFilter
7. Summary
This is the end of this article about the implementation of SpringCloud Gateway permission authentication. For more relevant SpringCloud Gateway permission authentication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!