依赖管理
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-r2dbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webfluxartifactId>
dependency>
<dependency>
<groupId>dev.mikugroupId>
<artifactId>r2dbc-mysqlartifactId>
<version>0.8.2.RELEASEversion>
dependency>
配置管理
spring:
r2dbc:
url: r2dbc:mysql://localhost:3306/testjpa?serverZoneId=GMT%2B8
username: root
password: 123123
pool:
initialSize: 100
maxSize: 200
maxCreateConnectionTime: 30s
---
logging:
level:
'[org.springframework.r2dbc]': DEBUG
实体对象,Repository,Service
@Table("t_users")
public class Users implements UserDetails {
@Id
private Integer id ;
private String username ;
private String password ;
}
这里实体对象实现了UserDetials,在后续配置的ReactiveUserDetailsService 配置返回值必须是UserDetails
Repository接口
public interface UsersRepository extends ReactiveSortingRepository<Users, String> {
Mono<Users> findByUsername(String username);
}
Service类
@Service
public class UsersService {
@Resource
private R2dbcEntityTemplate template;
@Resource
private UsersRepository ur ;
public Mono<Users> queryUserByUsername(String username) {
return ur.findByUsername(username) ;
}
public Mono<Users> queryUserByUsernameAndPassword(String username, String password) {
return ur.findByUsernameAndPassword(username, password) ;
}
public Flux<Users> queryUsers() {
return template.select(Users.class).all() ;
}
}
数据库中插入几条数据
单元测试
@SpringBootTest
class SpringBootWebfluxSecurity2ApplicationTests {
@Resource
private UsersService usersService ;
@Test
public void testQueryUserByUsername() throws Exception {
usersService.queryUserByUsername("admin")
.doOnNext(System.out::println)
.subscribe() ;
System.in.read() ;
}
}
输出
2023-01-12 17:43:48.863 DEBUG 16612 --- [ main] o.s.w.r.r.m.a.ControllerMethodResolver : ControllerAdvice beans: none
2023-01-12 17:43:48.896 DEBUG 16612 --- [ main] o.s.w.s.adapter.HttpWebHandlerAdapter : enableLoggingRequestDetails='false': form data and headers will be masked to prevent unsafe logging of potentially sensitive data
2023-01-12 17:43:49.147 INFO 16612 --- [ main] ringBootWebfluxSecurity2ApplicationTests : Started SpringBootWebfluxSecurity2ApplicationTests in 1.778 seconds (JVM running for 2.356)
2023-01-12 17:43:50.141 DEBUG 16612 --- [actor-tcp-nio-2] o.s.r2dbc.core.DefaultDatabaseClient : Executing SQL statement [SELECT t_users.id, t_users.username, t_users.password FROM t_users WHERE t_users.username = ?]
Users [id=3, username=admin, password=123123]
正常,接下来就是进行Security的配置
@Configuration
@EnableReactiveMethodSecurity
public class ReactiveSecurityConfig {
// 根据用户名查询用户信息
@Bean
public ReactiveUserDetailsService reativeUserDetailsService(UsersService usersService) {
return username -> usersService.queryUserByUsername(username).map(user -> {
return (UserDetails) user;
});
}
// 根据查询出的用户进行密码比对,没有对密码进行加密所有就进行简单的equals比较
@Bean
public PasswordEncoder passwordEncoder() {
return new PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
};
}
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
@Bean
public SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
http.authorizeExchange((authorize) ->
authorize
// 配置资源访问权限,对于静态资源直接放行
.pathMatchers("/resources/**", "/favicon.ico").permitAll()
// /users开头的接口必须拥有ROLE_ADMIN角色
.pathMatchers("/users/**").hasRole("ADMIN")
// /api开头的接口通过自定义验证逻辑控制
.pathMatchers("/api/**").access((authentication, context) -> {
return authentication.map(auth -> {
if ("user1".equals(auth.getName())) {
return new AuthorizationDecision(false);
}
MultiValueMapparams = context.getExchange().getRequest().getQueryParams();
Listsk = params.get("sk");
if (sk == null || sk.get(0).equals("u")) {
return new AuthorizationDecision(false);
}
return new AuthorizationDecision(true);
});
}).anyExchange().authenticated());
// 异常处理
http.exceptionHandling(execSpec -> {
// 无权限时响应策略
execSpec.accessDeniedHandler((exchange, denied) -> {
ServerHttpResponse response = exchange.getResponse() ;
response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
DataBuffer body = response.bufferFactory().allocateBuffer() ;
body.write("无权限 - " + denied.getMessage(), StandardCharsets.UTF_8) ;
return response.writeWith(Mono.just(body)) ;
}) ;
// 没有登录配置统一认证入口,这里默认系统提供的登录页面
execSpec.authenticationEntryPoint((exchange, ex) -> {
ServerHttpResponse response = exchange.getResponse() ;
response.getHeaders().add("Content-Type", "text/html;charset=UTF-8");
DataBuffer body = response.bufferFactory().allocateBuffer() ;
body.write("请先登录 - " + ex.getMessage(), StandardCharsets.UTF_8) ;
return response.writeWith(Mono.just(body)) ;
}) ;
}) ;
http.csrf(csrf -> csrf.disable());
http.formLogin();
return http.build();
}
}
以上就是Security的配置。这里就不做测试了
原理
这里对实现的原理做简单的接收,主要核心是WebFilter
自动配置类中
public class ReactiveSecurityAutoConfiguration {
// 这里通过注解启用了Security功能
@EnableWebFluxSecurity
static class EnableWebFluxSecurityConfiguration {
}
}
EnableWebFluxSecurity
@Import({ ServerHttpSecurityConfiguration.class, WebFluxSecurityConfiguration.class,
ReactiveOAuth2ClientImportSelector.class })
@Configuration
public @interface EnableWebFluxSecurity {
}
这里有个重要的ServerHttpSecurityConfiguration和WebFluxSecurityConfiguration配置类
@Configuration(proxyBeanMethods = false)
class ServerHttpSecurityConfiguration {
// 该类用来自定义配置我们的信息,也就是上面我们自定义的SecurityWebFilterChain
// 通过ServerHttpSecurity构建SecurityWebFilterChain
@Bean(HTTPSECURITY_BEAN_NAME)
@Scope("prototype")
ServerHttpSecurity httpSecurity() {
ContextAwareServerHttpSecurity http = new ContextAwareServerHttpSecurity();
return http.authenticationManager(authenticationManager())
.headers().and()
.logout().and();
}
}
WebFluxSecurityConfiguration
配置类最主要就是用来配置一个WebFilter
@Configuration(proxyBeanMethods = false)
class WebFluxSecurityConfiguration {
private ListsecurityWebFilterChains;
// 注入当前系统中的所有SecurityWebFilterChain,主要就是我们自定义实现的该类型
@Autowired(required = false)
void setSecurityWebFilterChains(ListsecurityWebFilterChains) {
this.securityWebFilterChains = securityWebFilterChains;
}
@Bean(SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME)
@Order(WEB_FILTER_CHAIN_FILTER_ORDER)
WebFilterChainProxy springSecurityWebFilterChainFilter() {
return new WebFilterChainProxy(getSecurityWebFilterChains());
}
private ListgetSecurityWebFilterChains() {
Listresult = this.securityWebFilterChains;
if (ObjectUtils.isEmpty(result)) {
return Arrays.asList(springSecurityFilterChain());
}
return result;
}
}
WebFilterChainProxy核心过滤器
public class WebFilterChainProxy implements WebFilter {
private final Listfilters;
@Override
public Monofilter(ServerWebExchange exchange, WebFilterChain chain) {
return Flux.fromIterable(this.filters)
.filterWhen((securityWebFilterChain) -> securityWebFilterChain.matches(exchange)).next()
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.flatMap((securityWebFilterChain) -> securityWebFilterChain.getWebFilters().collectList())
.map((filters) -> new FilteringWebHandler(chain::filter, filters)).map(DefaultWebFilterChain::new)
.flatMap((securedChain) -> securedChain.filter(exchange));
}
}
以上就是WebFlux中应用Security的原理