有两种方法
1、自定义页面
在继承WebSecurityConfigurerAdapter的配置类中重写的configure方法中,加上下面

//自定义403权限不足的页面
http.exceptionHandling().accessDeniedPage("/page/403.html");

2、自定义返回值,多用于前后端分离
新建一个类,实现AccessDeniedHandler 接口,并注入到容器中

@Component
public class MyAccessDenied implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        //设置响应数据格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //输入响应内容
        PrintWriter writer = httpServletResponse.getWriter();
        String json="{\"status\":\"403\",\"msg\":\"拒绝访问\"}";
        writer.write(json);
        writer.flush();

    }
}

然后在继承WebSecurityConfigurerAdapter的配置类中就可以@Autowired这个注入的类

//自定义403权限不足的返回值
 http.exceptionHandling().accessDeniedHandler(myAccessDenied);
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐