有没有办法在spring security webflux中包含定制的未授权响应消息?

biswetbf  于 2023-08-05  发布在  Spring
关注(0)|答案(2)|浏览(109)

我正在使用Sping Boot Webflux启动一个新项目,但现在我不知道如何处理401响应。
我想返回一个包含响应代码的消息体。响应代码正常,并按预期工作。现在,我如何注入消息体以给予更详细和描述性的响应,如下所示。

{
    "statusCode": "401",
    "statusMessage": "Unauthorized",
    "timestamp": "Sun May 07 10:30:23 GMT 2023"
}

字符串
这是我的Spring安全配置类的一部分:

@Bean
public SecurityWebFilterChain securityFilterChain(ServerHttpSecurity http) {
    return http
            .cors().and()
            .csrf().disable()
            //Disable Sessions
            .securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
            // handlers for 401 to return a 401 status, message and timestamp

            //rest services don't have a login form
            .formLogin()
            .disable()
            .authorizeExchange()
            .pathMatchers("/api/v1/get-token").hasRole("API")
            .and()
            .httpBasic()
            .and()
            .build();
}


一切都很好,我只想返回一个消息体JSON,而不仅仅是HTTP响应代码。有人知道吗

jei2mxaa

jei2mxaa1#

提供一个使用security提供的entryPoint的解决方案。相应的代码片段如下所示。
1.自定义入口点

public class CustomAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException authException) {
        // Custom error message or response body
        String errorMessage = "Unauthorized. Please authenticate.";

        // Set the status code and response body
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        exchange.getResponse().getHeaders().add("Content-Type", "application/json");
        return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory()
                .wrap(errorMessage.getBytes())));
    }
}

字符串
1.注册入口点

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    private final CustomAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    public SecurityConfig(CustomAuthenticationEntryPoint authenticationEntryPoint) {
        this.authenticationEntryPoint = authenticationEntryPoint;
    }

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                // Configure other security rules
                .build();
    }
}

fcipmucu

fcipmucu2#

您也可以使用全局异常处理来拦截AuthenticationException并返回自定义响应:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public CustomResponse handleAuthenticationException(AuthenticationException ex) {
        // Your custom response
        CustomResponse response = ...
        return response;
    }
}

字符串
您也可以从处理程序返回ResponseEntity<CustomResponse>,以便在需要时自定义响应头

相关问题