Spring WebFlux Security结合R2DBC实现权限控制

开发 前端
我们这里对实现的原理做简单的接收,主要核心是WebFilter。

环境:Springboot2.7.7

依赖管理

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
</dependency>
<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>
<dependency>
<groupId>dev.miku</groupId>
<artifactId>r2dbc-mysql</artifactId>
<version>0.8.2.RELEASE</version>
</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);
}
MultiValueMap<String, String> params = context.getExchange().getRequest().getQueryParams();
List<String> sk = 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 List<SecurityWebFilterChain> securityWebFilterChains;
// 注入当前系统中的所有SecurityWebFilterChain,主要就是我们自定义实现的该类型
@Autowired(required = false)
void setSecurityWebFilterChains(List<SecurityWebFilterChain> securityWebFilterChains) {
this.securityWebFilterChains = securityWebFilterChains;
}
@Bean(SPRING_SECURITY_WEBFILTERCHAINFILTER_BEAN_NAME)
@Order(WEB_FILTER_CHAIN_FILTER_ORDER)
WebFilterChainProxy springSecurityWebFilterChainFilter() {
return new WebFilterChainProxy(getSecurityWebFilterChains());
}
private List<SecurityWebFilterChain> getSecurityWebFilterChains() {
List<SecurityWebFilterChain> result = this.securityWebFilterChains;
if (ObjectUtils.isEmpty(result)) {
return Arrays.asList(springSecurityFilterChain());
}
return result;
}
}

WebFilterChainProxy核心过滤器

public class WebFilterChainProxy implements WebFilter {

private final List<SecurityWebFilterChain> filters;
@Override
public Mono<Void> filter(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的原理

责任编辑:武晓燕 来源: 实战案例锦集
相关推荐

2023-09-21 08:01:27

SpringR2DBC实现数据库

2022-03-29 07:32:38

R2DBC数据库反应式

2022-08-30 08:50:07

Spring权限控制

2022-08-15 08:45:21

Spring权限控制

2022-08-30 08:43:11

Spring权限控制

2022-08-30 08:36:13

Spring权限控制

2022-08-30 08:55:49

Spring权限控制

2022-08-15 08:42:46

权限控制Spring

2022-06-16 10:38:24

URL权限源代码

2020-05-08 10:34:30

Spring非阻塞编程

2024-02-18 12:44:22

2020-06-17 08:31:10

权限控制Spring Secu

2021-07-27 10:49:10

SpringSecurity权限

2020-09-16 08:07:54

权限粒度Spring Secu

2011-03-01 16:44:02

Hyper-V Ser

2022-01-07 07:29:08

Rbac权限模型

2022-11-04 11:44:56

WebFluxCURDWeb

2020-05-25 07:00:00

双因素认证身份认证密码

2023-09-04 11:52:53

SpringMVC性能

2022-07-04 09:15:10

Spring请求处理流程
点赞
收藏

51CTO技术栈公众号