my security microservice is working fine when i register a user it is saved in my database and when loging in a jwt is generated
the security service is meant to protect a search api service that is also working just fine, now the last step which is using the api gateway to filter resuests, is the problem because it allows every request and returns the wantes results even if i am not passing any bearer token
my API gateway:
- the api gateway configuration;
package ma.attijari.apigateway;
import io.netty.resolver.DefaultAddressResolverGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
@EnableDiscoveryClient
@Configuration
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
//System.out.println("helloooo");
}
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
System.out.println("helloooo");
return builder.routes()
.route("SecurityService", r -> r
.path("SecurityService/**")
.filters(f -> f.filter(jwtAuthenticationFilter).stripPrefix(1))
.uri("lb://SecurityService"))
.route("ESSearchAPI", r -> r
.path("ESSearchAPI/**")
.filters(f -> f.filter(jwtAuthenticationFilter).stripPrefix(1))
.uri("lb://ESSearchAPI"))
.build();
}
@Bean
@Primary
public WebClient webClient() {
HttpClient httpClient = HttpClient.create().resolver(DefaultAddressResolverGroup.INSTANCE);
return WebClient.builder()
.clientConnector(new ReactorClientHttpConnector(httpClient))
.build();
}
}
- the jwt filter:
package ma.attijari.apigateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class JwtAuthenticationFilter implements GatewayFilter, Ordered {
@Autowired
private SecurityServiceClient securityServiceClient;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
System.out.println("authHeader: " + authHeader);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
System.out.println("token: " + token);
return securityServiceClient.validateToken(token)
.flatMap(isValid -> {
if (isValid) {
return chain.filter(exchange); // Token is valid, proceed with the request
} else {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete(); // Token is invalid, reject the request
}
});
} else {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete(); // No token provided, reject the request
}
}
@Override
public int getOrder() {
return -100; // Ensure this filter runs before others
}
}
i also had an error with the mapping so i added this config as well:
spring:
cloud:
gateway:
routes:
- id: ESSearchAPI
predicates:
- Path=/ESSearchAPI/** # Match any sub-paths under /ESSearchAPI/
uri: http://localhost:6543
filters:
- StripPrefix=1 # Remove /ESSearchAPI before forwarding
- id: SecurityService
predicates:
- Path=/SecurityService/** # Match any sub-paths under /ESSearchAPI/
uri: http://localhost:5432
filters:
- StripPrefix=1 # Remove /ESSearchAPI before forwarding
- the eureka discoveru client
- the security controller:
package ma.attijari.apigateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private SecurityServiceClient securityServiceClient;
@PostMapping("/validate-token")
public ResponseEntity<Boolean> validateToken(@RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader) {
return ResponseEntity.ok(securityServiceClient.validateToken(authHeader).block());
}
}
- the SecurityServiceClient
package ma.attijari.apigateway;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
@Service
public class SecurityServiceClient {
private final WebClient webClient;
public SecurityServiceClient(WebClient.Builder webClientBuilder) {
this.webClient = webClientBuilder.baseUrl("https://localhost:5432").build();
}
public Mono<Boolean> validateToken(String token) {
return webClient.post()
.uri("/api/auth/validate-token") // Adjust this URI to match your security service endpoint
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.retrieve()
.bodyToMono(Boolean.class)
.onErrorResume(WebClientResponseException.class, ex -> {
if (ex.getStatusCode() == HttpStatus.UNAUTHORIZED) {
return Mono.just(false);
}
return Mono.error(ex);
});
}
}
- and in the security service side this is the token validation logic(note that other functionnalities are working just fine and tested)
6.a. authcontroller:
package ma.attijari.securityservice.controllers;
import ma.attijari.securityservice.dtos.LoginRequest;
import ma.attijari.securityservice.service.JwtService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "http://localhost:4200")
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtService jwtService;
public AuthController(AuthenticationManager authenticationManager, JwtService jwtService) {
this.authenticationManager = authenticationManager;
this.jwtService = jwtService;
}
@GetMapping("/hello")
public String hello() {
return "Hello World";
}
@PostMapping("/login")
public ResponseEntity<Map<String,String>> login(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())
);
Map<String, String> token = new HashMap<>();
token.put("token", jwtService.generateToken(authentication));
return ResponseEntity.ok(token);
}
//validate token endpoint
@PostMapping("/validate-token")
public ResponseEntity<Boolean> validateToken(@RequestHeader(HttpHeaders.AUTHORIZATION) String authHeader) {
return this.jwtService.validateHttpToken(authHeader);
}
}
6.b.service:
package ma.attijari.securityservice.service;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.AllArgsConstructor;
import ma.attijari.securityservice.config.RsaKeyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.jwt.*;
import org.springframework.stereotype.Service;
import java.security.Key;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import javax.crypto.SecretKey;
@Service
@AllArgsConstructor
public class JwtService {
private final JwtEncoder jwtEncoder;
private final JwtDecoder jwtDecoder;
@Autowired
private RsaKeyConfig rsaKeyConfig;
// Generate JWT token
public String generateToken(Authentication authentication) {
Instant now = Instant.now();
String scope = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("self")
.issuedAt(now)
.expiresAt(now.plus(1, ChronoUnit.HOURS))
.subject(authentication.getName())
.claim("scope", scope)
.build();
return this.jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
}
public boolean validateToken(String token) {
try {
Jwt jwt = jwtDecoder.decode(token);
Instant now = Instant.now();
if (jwt.getExpiresAt().isBefore(now)) {
return false;
}
if (!"self".equals(jwt.getIssuer().toString())) {
return false;
}
return true;
} catch (JwtException e) {
return false; // Token is invalid
}
}
// API method to validate token via a REST call
public ResponseEntity<Boolean> validateHttpToken(String authHeader) {
if (authHeader != null && authHeader.startsWith("Bearer ")) {
String token = authHeader.substring(7);
return ResponseEntity.ok(validateToken(token));
}
return ResponseEntity.ok(false);
}
}
the test (with no authorization header)
i want to protect the search api, i don’t want the apigateway to allow any requests unless a valid jwt is provided in the header