Spring WebFlux安全定制AccessDeniedHandler

时间:2018-10-25 01:59:51

标签: spring spring-security kotlin spring-webflux

我有一个REST端点,其中的访问仅限于ADMIN用户:

@GetMapping
@PreAuthorize("hasAuthority('ADMIN')")
fun getAll(): Flux<User> {
    return Flux.fromIterable(userRepository.findAll())
}

当我尝试使用非ADMIN用户访问此终结点时,我收到一个带有denied响应(非JSON响应)的403。

如何自定义响应以仍然收到403响应,但带有类似JSON消息的

{
   "error": "Access denied"
}

我正在实施的SecurityWebFilterChain

return http.csrf().disable()
    .formLogin().disable()
    .httpBasic().disable()
    .authenticationManager(authenticationManager)
    .securityContextRepository(securityContextRepository)
    .exceptionHandling().accessDeniedHandler { exchange, denied -> ???? }
    .and()
    .authorizeExchange()
    .pathMatchers(HttpMethod.OPTIONS).permitAll()
    .pathMatchers("/auth").permitAll()
    .anyExchange().authenticated()
    .and().csrf().disable()
    .logout().disable()
    .build()

1 个答案:

答案 0 :(得分:0)

您可以创建自定义过滤器,并在收到403错误时修改响应。 像这样:

class AuthorizationModifierFilter : Filter {
    ....

    fun doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit {
        // Check whether the status code is 403 and modify the response
    }
}

并注册您的过滤器:

return http.csrf().disable()
    .formLogin().disable()
    .httpBasic().disable()
    .authenticationManager(authenticationManager)
    .securityContextRepository(securityContextRepository)
    .exceptionHandling().accessDeniedHandler { exchange, denied -> ???? }
    .and()
    .authorizeExchange()
    .pathMatchers(HttpMethod.OPTIONS).permitAll()
    .pathMatchers("/auth").permitAll()
    .anyExchange().authenticated()
    .and().addFilterAfter(AuthorizationModifierFilter(), UsernamePasswordAuthenticationFilter.java.class)
    .and().csrf().disable()
    .logout().disable()
    .build()