Spring security中自定义403页面(没有权限跳转自定义页面)

该博客介绍了如何在Spring Security中配置自定义的权限拒绝页面,通过`http.exceptionHandling().accessDeniedPage(/error.html)`设置未授权访问时跳转到的错误页面。此外,还展示了完整的配置代码,包括登录页面设置、路径权限控制、鉴权策略以及关闭CSRF防护等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在configure(HttpSecurity http)方法中加入

http.exceptionHandling().accessDeniedPage("/error.html");//配置没有权限访问跳转的自定义页面

整体方法如下

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/error.html");//配置没有权限访问跳转的自定义页面
        http.formLogin() //自定义编写的登录页面
            .loginPage("/login.html")//登录页面设置
            .loginProcessingUrl("/user/login")//登录后访问路径
            .defaultSuccessUrl("/test/index")//登录成功后跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .antMatchers("/test/index").hasAnyRole("sale,master")//具有ROLE_sale,ROLE_master的角色可以访问这个路径
                .anyRequest().authenticated()//除上面外的所有请求全部需要鉴权认证
                .and().csrf().disable();//关闭csrf防护
    }

    @Bean
    PasswordEncoder password()
    {
        return new BCryptPasswordEncoder();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值