gpt4 book ai didi

java - Spring Boot : How could I customize the forbidden error json

转载 作者:行者123 更新时间:2023-12-04 01:52:09 27 4
gpt4 key购买 nike

我想知道是否可以自定义以下禁止的 JSON 错误:

实际 react

{
"timestamp": "2018-09-26T06:11:05.047+0000",
"status": 403,
"error": "Forbidden",
"message": "Access Denied",
"path": "/api/rest/hello/me"
}

自定义响应 - 当用户请求没有权限时我得到它。
{ 
"code": 403,
"message": "Access denied by the system",
"status": "Failure"
}

我的网络安全课
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtTokenProvider jwtTokenProvider;

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()//
.antMatchers("/rest/hello/signin").permitAll()//
.anyRequest().authenticated();
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
}

最佳答案

您可以使用 Jackson 创建自定义处理程序ObjectMapper像这样:

@Bean
public AccessDeniedHandler accessDeniedHandler() {
return (request, response, ex) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);

ServletOutputStream out = response.getOutputStream();
new ObjectMapper().writeValue(out, new MyCustomErrorDTO());
out.flush();
};
}

并配置您的 HttpSecurity像这样:
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());

另外,您可以尝试抛出 AuthenticationException :
@Bean
public AuthenticationFailureHandler failureHandler() {
return (request, response, ex) -> { throw ex; };
}

并在 @RestControllerAdvice 中处理它们:
@RestControllerAdvice
public class AdviseController {

@ExceptionHandler(AuthenticationException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public MyCustomErrorDTO handleAuthenticationException(AuthenticationException ex) {
return new MyCustomErrorDTO();
}
}

但我不确定它会起作用,你可以检查一下。

关于java - Spring Boot : How could I customize the forbidden error json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52511324/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com