Spring RESTApi, Spring Security 自定义403返回信息

来源:互联网 发布:json编辑 编辑:程序博客网 时间:2024/06/07 03:26

在普通的Java web 项目中,如果使用了spring security 的话,直接在application配置文件中,指定一个403error-page。
如果项目只提供restapi,也就不存在error-page这个概念甚至page这个说法了。如果请求一个没有权限的资源时,会返回一个默认的html页面。显然这不符合restapi的需要。
这种情况下,我们需要自定义一个AccessDeniedHandler:

public class RestAuthenticationAccessDeniedHandler implements AccessDeniedHandler {    @Override    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)            throws IOException, ServletException {        response.setStatus(HttpServletResponse.SC_FORBIDDEN);        PrintWriter writer = response.getWriter();        writer.println(accessDeniedException.getMessage());    }}

然后在WebSecurityConfigurerAdapter的实现类中注册这个处理器:

@Beanpublic AccessDeniedHandler getAccessDeniedHandler() {    return new RestAuthenticationAccessDeniedHandler();}

最后,在实现类重写的config()方法中,添加对处理器的使用:

@Overrideprotected void configure(HttpSecurity http) throws Exception {    http.exceptionHandling().accessDeniedHandler(getAccessDeniedHandler());}

效果图