Handle Security exceptions in Spring Boot Resource Server

后端 未结 8 685
执念已碎
执念已碎 2021-01-31 05:36

How can I get my custom ResponseEntityExceptionHandler or OAuth2ExceptionRenderer to handle Exceptions raised by Spring security on a pure resource ser

8条回答
  •  故里飘歌
    2021-01-31 05:54

    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
      @Override
      public void commence(HttpServletRequest request, HttpServletResponse res,
            AuthenticationException authException) throws IOException, ServletException {
          ApiException ex = new ApiException(HttpStatus.FORBIDDEN, "Invalid Token", authException);
    
          ObjectMapper mapper = new ObjectMapper();
          res.setContentType("application/json;charset=UTF-8");
          res.setStatus(403);
          res.getWriter().write(mapper.writeValueAsString(ex));
      }
    }
    

提交回复
热议问题