首页 > 解决方案 > Spring Webflux Security 中的角色层次结构

问题描述

我通过实施以下方式实施了 Webflux 安全性:

现在,我正在尝试按照此处的文档介绍 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);
}

正常的角色授权对我有用,不工作的是层次结构部分。

标签: springspring-bootspring-securityspring-webflux

解决方案


我能够在 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);
}

推荐阅读