SpringSecurity——Web权限方案用户授权(自定义403页面)

在Spring Security中,当用户尝试访问其没有权限的资源时,系统会返回一个HTTP状态码为403的错误页面。可以自定义403页面来提供更友好的用户体验。

详细步骤如下:

  1. 创建自定义403页面:创建一个自定义的403页面,例如forbidden.html。

  2. 配置访问规则:配置Spring Security,指定访问受限资源时跳转到自定义的403页面。

代码如下:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .exceptionHandling()
                .accessDeniedPage("/403");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("admin")
            .password(passwordEncoder().encode("admin123"))
            .roles("ADMIN")
            .and()
            .withUser("user")
            .password(passwordEncoder().encode("user123"))
            .roles("USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

在上面的代码中,通过 configure() 方法配置了自定义403页面。指定了访问受限资源时跳转到"/403"页面。在 configure() 方法中,配置了两个用户信息,一个是具有"ADMIN"角色的"admin"用户,另一个是具有"USER"角色的"user"用户。

通过这样的配置,当用户尝试访问其没有权限的资源时,系统会返回一个HTTP状态码为403,并跳转到自定义的403页面提供友好的提示信息。这种方式可以实现自定义403页面的需求。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值