[英]Spring boot : How could I customize the forbidden error json
我想知道是否可以自定義以下禁止的 JSON 錯誤:
實際反應
{
"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();
}
}
但我不確定它會起作用,你可以檢查一下。
為了顯示自定義消息,我為 JWT Security 創建了入口點類 JwtAuthenticationEntryPoint。
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
AuthenticationException e) throws IOException, ServletException {
logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
"Sorry, You're not authorized to access this resource.");
}
}
並作為入口點傳遞到安全配置,例如,
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("auth/singIn" , "auth/singUp/")
.permitAll().anyRequest().authenticated();
}
}
或者您可以使用@ControllerAdvice 和自定義異常處理來處理自定義或系統異常
在您的控制器或 ExceptionHandler 中添加:
@ExceptionHandler(AccessDeniedException.class)
public @ResponseBody ResponseEntity<AuthzErrorResponse> handlerAccessDeniedException(final Exception ex,
final HttpServletRequest request, final HttpServletResponse response) {
AuthzErrorResponse authzErrorResponse = new AuthzErrorResponse();
authzErrorResponse.setMessage("Access denied");
return new ResponseEntity<>(authzErrorResponse, HttpStatus.FORBIDDEN);
}
注意:AuthzErrorResponse 是我想要返回的自定義 POJO。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.