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());
}

效果图

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值