Spring Security的自定义403的方式

有两种方法
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);
自定义Spring Security中的403错误页面,可以按照以下步骤进行操作: 1. 创建一个403.html页面,用于显示自定义错误信息。 2. 创建一个自定义的AccessDeniedHandler类,用于处理访问被拒绝的情况。 3. 在Spring Security配置文件中配置AccessDeniedHandler,指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。 以下是一个简单的示例代码: 1. 创建403.html页面 ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Access Denied</title> </head> <body> <h1>Access Denied</h1> <p>You are not authorized to access this resource.</p> </body> </html> ``` 2. 创建自定义的AccessDeniedHandler类 ``` @Component public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException { response.sendRedirect("/403.html"); } } ``` 3. 在Spring Security配置文件中配置AccessDeniedHandler ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAccessDeniedHandler accessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .and() .exceptionHandling().accessDeniedHandler(accessDeniedHandler); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER") .and() .withUser("admin").password("password").roles("USER", "ADMIN"); } } ``` 以上代码中,CustomAccessDeniedHandler类是自定义的AccessDeniedHandler实现类,它在处理访问被拒绝的情况时,通过重定向到403.html页面来显示自定义错误信息。在SecurityConfig配置类中,通过exceptionHandling().accessDeniedHandler(accessDeniedHandler)方法来指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值