Reputation: 29
I have two microservices: Gateway and HelloWorld. I use Basic Auth which occurs in the Gateway microservice. Then the request is routed to the HelloWorld microservice. But here's the problem: the request is routed but the Authentication is not.
HelloWorld
@RequestMapping("/")
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
@GetMapping("/secured")
public String secured(Authentication auth) {
// !!! auth == null -> NullPointerException !!!
return "This page is secured. Your role is "
+ auth.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(", ")) + ".";
}
}
Gateway
@Configuration
@EnableWebFluxSecurity
public class WebSecurityConfig {
@Bean
public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http, ReactiveAuthenticationManager authManager) throws Exception {
return http
.authorizeExchange(request -> request
.pathMatchers("/hello").permitAll()
.pathMatchers("/secured").authenticated()
.anyExchange().permitAll()
)
.csrf(csrf -> csrf.disable())
.httpBasic(httpBasic -> httpBasic.authenticationManager(authManager))
.build();
}
// some security configuration ...
}
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route(p -> p
.path("/**")
.uri("http://localhost:8081"))
.build();
}
}
What I want to find out:
P.S. Please don't answer "You should use JWT" or something. I want to find the solution in my current situation (using Basic Auth). But I'll be glad to receive some recommendations along with the answer to my questions. :)
Upvotes: 0
Views: 60
Reputation: 1
The front-end stores user information in a cookie and passes it to the gateway. After the gateway parses the user information, it sets information such as username userId in the header or cookie. The services after the gateway extract user information directly from the header/cookie. This is my simple plan, you can make modifications according to your own needs. Hope it's helpful to you.
Upvotes: 0