我刚开始学习Spring的新反应式编程模型,因此尝试编写了一个非常基本的Web服务。
这是我的应用程序配置:
@SpringBootApplication
@EnableWebFluxSecurity
public class ReactiveSpringApplication {
public static void main(final String[] args) {
SpringApplication.run(ReactiveSpringApplication.class, args);
}
@Bean
public ReactiveUserDetailsService userDetailsService() {
final UserDetails admin = User.withDefaultPasswordEncoder().username("admin").password("password").roles("ADMIN").build();
final UserDetails user = User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build();
return new MapReactiveUserDetailsService(admin, user);
}
@Bean
public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity httpSecurity) {
return httpSecurity
.authorizeExchange()
.anyExchange().authenticated().and()
.httpBasic().and()
.build();
}
@Bean
public HttpHandler httpHandler() {
final RouterFunction<ServerResponse> routes = route(GET("/"), serverRequest ->
ServerResponse.ok().body(just("{\"message\":\"Hello world!\"}"), String.class));
return RouterFunctions.toHttpHandler(routes);
}
}
目前这是我的依赖关系:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
当我向
http://localhost:8080/
发送GET
请求时,我会收到一个200 OK
响应,并在正文中得到{"message":"Hello world!"}
。然而,我预期会收到401 Unauthorized
响应。在securityWebFilterChain()
方法内构建的MatcherSecurityWebFilterChain
未被调用,因此未执行任何安全规则。为了解决这个问题,我需要做出什么改变?