环境:Springboot2.5.8
请先阅读:
Spring WebFlux入门实例并整合数据库实现基本的增删改查
简介
Spring Security的WebFlux支持依赖于WebFilter,对Spring WebFlux和Spring WebFlux.Fn的作用相同。WebMVC依赖于Filter。
依赖管理
<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>
安全配置
@Configuration
@EnableReactiveMethodSecurity
public class WebfluxSecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
// 配置一个基于内存的用户名
UserDetails user = new Users() ;
return new MapReactiveUserDetailsService(user);
}
// 密码编码器
@Bean
public PasswordEncoder passwordEncoder() {
return new PasswordEncoder() {
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.equals(encodedPassword) ;
}
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString() ;
}
};
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.csrf(csrf -> csrf.disable()) ;
http.authorizeExchange(exchanges -> {
exchanges.pathMatchers(HttpMethod.GET, "/css/**", "/resources/**").permitAll() ;
exchanges.pathMatchers("/users/**").hasRole("ADMIN") ;
exchanges.anyExchange().authenticated();
}) ;
// 配置默认的登录
http.formLogin();
http.exceptionHandling(exceptionHandling -> {
exceptionHandling.accessDeniedHandler((exchange, denied) -> {
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap("Access Denied".getBytes()) ;
return exchange.getResponse().writeAndFlushWith(Mono.just(Mono.just(buffer))) ;
}) ;
}) ;
return http.build();
}
}
路由配置
基于Functional Endpoint配置路由信息
@Configuration
public class RouterConfig {
@Bean
public RouterFunction<ServerResponse> usersRouter() {
return RouterFunctions.route().GET("/users/{id}", request -> {
System.out.println("查询:" + request.pathVariable("id")) ;
return ServerResponse.ok().bodyValue(new Users()) ;
}).build() ;
}
}
方法安全验证
@RestController
@RequestMapping("/antUsers")
public class UsersController {
@GetMapping("/index")
@PreAuthorize("hasRole('10000')")
public Mono<String> index() {
return Mono.just("success") ;
}
}
完毕!!!