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

在普通的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的实现类中注册这个处理器:

@Bean
public AccessDeniedHandler getAccessDeniedHandler() {
    return new RestAuthenticationAccessDeniedHandler();
}

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

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

效果图

猜你喜欢

转载自blog.csdn.net/jiangshanwe/article/details/73234988