1. 程式人生 > 其它 >SpringSecurity自定義響應異常資訊

SpringSecurity自定義響應異常資訊

SpringSecurity自定義響應異常資訊

此處的異常資訊設定的話,其中還是有坑的,比如你想自定義token過期資訊,無效token這些,如果按照SpringSecurity的設定是不會生效的,需要加到資源的配置中。

如果只是SpringSecurity的話,只需要實現AccessDeniedHandler和AuthenticationEntryPoint這2個介面就可以了。他們都是在ExceptionTranslationFilter中生效的。

AuthenticationEntryPoint 用來解決匿名使用者訪問無許可權資源時的異常

ruAccessDeineHandler 用來解決認證過的使用者訪問無許可權資源時的異常

如果你想自定義token過期的話,需要實現AuthenticationEntryPoint這個介面,因為token過期了,訪問的話也算是匿名訪問。但是SpringSecurity的過濾器鏈中其實是有順序的,校驗token的OAuth2AuthenticationProcessingFilter在它前面,導致一直沒有辦法生效,所有需要新增到資源的配置上,demo如下:

/**
 * @author WGR
 * @create 2021/8/23 -- 16:52
 */
@Component
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        Throwable cause = authException.getCause();
        try {
            if (cause instanceof InvalidTokenException) {
                Map map = new HashMap();
                map.put("error", "無效token");
                map.put("message", authException.getMessage());
                map.put("path", request.getServletPath());
                map.put("timestamp", String.valueOf(new Date().getTime()));
                response.setContentType("application/json");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.writeValue(response.getOutputStream(), map);
                } catch (Exception e) {
                    throw new ServletException();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

則可以生效,返回資訊具體如下:

如果想設定沒有許可權的自定義異常資訊的話:

/**
 * @author WGR
 * @create 2021/8/23 -- 17:09
 */
@Component
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Map map = new HashMap();
        map.put("message", "無權操作");
        map.put("path", request.getServletPath());
        map.put("timestamp", String.valueOf(new Date().getTime()));
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

把它設定到springsecurity中,新增進去就可以了,如果不是想要捕獲token過期的話,就直接新增進去也可以