|
| 1 | +package com.streamseat.apigateway.filter; |
| 2 | + |
| 3 | +import org.springframework.http.HttpHeaders; // Use Spring's HttpHeaders |
| 4 | +import com.streamseat.apigateway.utils.JwtUtil; |
| 5 | +import org.springframework.beans.factory.annotation.Autowired; |
| 6 | +import org.springframework.cloud.gateway.filter.GatewayFilter; |
| 7 | +import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; |
| 8 | +import org.springframework.http.server.reactive.ServerHttpRequest; |
| 9 | +import org.springframework.stereotype.Component; |
| 10 | + |
| 11 | +@Component |
| 12 | +public class AuthenticationFilter extends AbstractGatewayFilterFactory<AuthenticationFilter.Config> { |
| 13 | + |
| 14 | + @Autowired |
| 15 | + private RouteValidator validator; // Simple class to skip auth for /login or /register |
| 16 | + @Autowired |
| 17 | + private JwtUtil jwtUtil; |
| 18 | + |
| 19 | + public AuthenticationFilter() { |
| 20 | + super(Config.class); |
| 21 | + } |
| 22 | + |
| 23 | + @Override |
| 24 | + public GatewayFilter apply(Config config) { |
| 25 | + return ((exchange, chain) -> { |
| 26 | + if (validator.isSecured.test( exchange.getRequest())) { |
| 27 | + // 1. Check Header |
| 28 | + if (!exchange.getRequest().getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { |
| 29 | + throw new RuntimeException("Missing Authorization Header"); |
| 30 | + } |
| 31 | + |
| 32 | + String authHeader = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); |
| 33 | + if (authHeader != null && authHeader.startsWith("Bearer ")) { |
| 34 | + authHeader = authHeader.substring(7); |
| 35 | + } |
| 36 | + |
| 37 | + try { |
| 38 | + // 2. Validate |
| 39 | + jwtUtil.validateToken(authHeader); |
| 40 | + |
| 41 | + // 3. Extract & Inject Header for internal microservices |
| 42 | + String userId = jwtUtil.extractUserId(authHeader); |
| 43 | + ServerHttpRequest request = exchange.getRequest() |
| 44 | + .mutate() |
| 45 | + .header("X-User-Id", userId) |
| 46 | + .build(); |
| 47 | + |
| 48 | + return chain.filter(exchange.mutate().request(request).build()); |
| 49 | + |
| 50 | + } catch (Exception e) { |
| 51 | + throw new RuntimeException("Unauthorized access"); |
| 52 | + } |
| 53 | + } |
| 54 | + return chain.filter(exchange); |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + public static class Config {} |
| 59 | +} |
0 commit comments