spring - Spring Webflux Security 中的角色层次结构
问题描述
我通过实施以下方式实施了 Webflux 安全性:
- ReactiveUserDetailsService
- 反应式身份验证管理器
- 服务器安全上下文存储库
现在,我正在尝试按照此处的文档介绍 RoleHierarchy:Role Hierarchy Docs
我有一个角色为 USER 的用户,但他在点击带有 GUEST 角色注释的控制器时收到 403 Denied。角色层次结构是:“ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST”
@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
private final DaoAuthenticationManager reactiveAuthenticationManager;
private final SecurityContextRepository securityContextRepository;
private static final String ROLE_HIERARCHIES = "ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST";
@Autowired
public SecurityConfig(DaoAuthenticationManager reactiveAuthenticationManager,
SecurityContextRepository securityContextRepository) {
this.reactiveAuthenticationManager = reactiveAuthenticationManager;
this.securityContextRepository = securityContextRepository;
}
@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.formLogin().disable()
.httpBasic().disable()
.authenticationManager(reactiveAuthenticationManager)
.securityContextRepository(securityContextRepository)
.authorizeExchange()
.anyExchange().permitAll()
.and()
.logout().disable()
.build();
}
@Bean(name = "roleHierarchy")
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(ROLE_HIERARCHIES);
return roleHierarchy;
}
@Bean(name = "roleVoter")
public RoleVoter roleVoter() {
return new RoleHierarchyVoter(roleHierarchy());
}
}
@Component
public class DaoAuthenticationManager implements ReactiveAuthenticationManager {
private final DaoUserDetailsService userDetailsService;
private final Scheduler scheduler;
@Autowired
public DaoAuthenticationManager(DaoUserDetailsService userDetailsService,
Scheduler scheduler) {
Assert.notNull(userDetailsService, "userDetailsService cannot be null");
this.userDetailsService = userDetailsService;
this.scheduler = scheduler;
}
@Override
public Mono<Authentication> authenticate(Authentication authentication) {
final String username = authentication.getName();
return this.userDetailsService.findByUsername(username)
.publishOn(this.scheduler)
.switchIfEmpty(
Mono.defer(() -> Mono.error(new UsernameNotFoundException("Invalid Username"))))
.map(u -> new UsernamePasswordAuthenticationToken(u, u.getPassword(),
u.getAuthorities()));
}
}
@Component
public class SecurityContextRepository implements ServerSecurityContextRepository {
private final DaoAuthenticationManager authenticationManager;
@Autowired
public SecurityContextRepository(DaoAuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Mono<Void> save(ServerWebExchange swe, SecurityContext sc) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Mono<SecurityContext> load(ServerWebExchange swe) {
ServerHttpRequest request = swe.getRequest();
if (request.getHeaders().containsKey("userName") &&
!Objects.requireNonNull(request.getHeaders().get("userName")).isEmpty()) {
String userName = Objects.requireNonNull(swe
.getRequest()
.getHeaders()
.get("userName")).get(0);
Authentication auth = new UsernamePasswordAuthenticationToken(userName,
Security.PASSWORD);
return this.authenticationManager.authenticate(auth).map(SecurityContextImpl::new);
} else {
return Mono.empty();
}
}
}
无论如何,要让角色层次结构在 Webflux 安全中工作。
编辑
控制器:
@GetMapping
@PreAuthorize("hasRole('USER')")
public Mono<Device> getDevice(@RequestParam String uuid) {
return deviceService.getDevice(uuid);
}
正常的角色授权对我有用,不工作的是层次结构部分。
解决方案
我能够在 Webflux 中实现角色层次结构的一种方法是创建自定义注释。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('ADMIN')")
public @interface IsAdmin {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAnyRole('ADMIN', 'USER')")
public @interface IsUser {
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAnyRole('ADMIN', 'USER', 'GUEST')")
public @interface IsGuest {
}
––––––––––––––––––––––––</p>
并像这样注释控制器:
@GetMapping
@IsUser
public Mono<Device> getDevice(@RequestParam String uuid) {
return deviceService.getDevice(uuid);
}
@PostMapping
@IsAdmin
@ResponseStatus(HttpStatus.CREATED)
public Mono<Device> createDevice(@Valid @RequestBody Device device) {
return deviceService.createDevice(device);
}
推荐阅读
- python - Pandas:有没有办法将列中的值组合在一起?
- vba - 在 R1C1 公式中使用时,带小数的变量会转换为 2 位数字
- r - 在不丢失信息的情况下减少数据
- javascript - Scriptable Java Transform Spring 云数据流
- lua - Lua - 难以理解 OOP
- excel - Excel 2016 VBA - 状态栏未显示完整消息
- angularjs - $scope.$on $locationChangeStart 保留 URL 但显示新视图
- java - Spring boot 2 - REST 控制器测试在 org.springframework.hateoas.PagedResources 上引发异常
- java - 为什么根据 Cmake,Java OpenCV 模块不可用?
- prometheus - 为什么在没有匹配原始数据的情况下`count_over_time`会增加?