您当前的位置: 首页 >  spring

梁云亮

暂无认证

  • 3浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot+SpringSecurity系列七:自定义403页面

梁云亮 发布时间:2022-01-07 15:39:59 ,浏览量:3

403简介

403 Forbidden - 拒绝访问 403 Forbidden 是HTTP协议中的一个状态码(Status Code)。可以简单的理解为没有权限访问此站。 该状态表示服务器理解了本次请求但是拒绝执行该任务,该请求不该重发给服务器。在HTTP请求的方法不是“HEAD”,并且服务器想让客户端知道为什么没有权限的情况下,服务器应该在返回的信息中描述拒绝的理由。在服务器不想提供任何反馈信息的情况下,服务器可以用404 Not Found代替403 Forbidden。

第一步:在resources目录中创建403.html
DOCTYPE html>


  
  403


403


第二步:在Controller中添加对应的跳转控制
@GetMapping("/open403")
String open403() {
    return "403";
}
第三步:自定义AccessDeniedHandler
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.sendRedirect(request.getContextPath()+"/open403");
    }
}
第四步:修改SpringSecurity配置文件
@Resource
private MyAccessDeniedHandler myAccessDeniedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin() //表单登录
            .usernameParameter("username123")
            .passwordParameter("password234")
            .loginPage("/openLogin") //设置登录页面对应的地址,默认是/login
            .loginProcessingUrl("/userLogin") //设置用户登录时请求的地址,默认是/login
            .and()
            .authorizeRequests()
            //授权
            .antMatchers("/openLogin").anonymous()//toLogin放行:不需要拦截,可以随便访问
            .anyRequest().authenticated()//其它请求都必须认证后才能访问
            .and()
            // 用户没有权限的页面处理
            .exceptionHandling()
            .accessDeniedHandler(myAccessDeniedHandler)   //配置403访问错误处理器
            .and()
            //关闭防火墙:为了保证完整流程可用关闭CSRF安全协议
            .csrf().disable();
}
测试

用户先登录,登录成功之后再次访问登录页面,就会打开403页面

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0435s