Spring Security旧版本使用与新版本使用对比

旧版本:

Security配置类

@Configuration
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    /**
     * 创建 BCryptPasswordEncoder 对象,并且将其注入IOC容器中。
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置相关的过滤器链设置,并注入IOC容器中。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/unauth"); // 自定义403页面
        http.formLogin() // 自定义登陆页面
                .loginPage("/login.html") // 设置登陆页面
                .loginProcessingUrl("/login") // 登录访问路径
                .defaultSuccessUrl("/index").permitAll() // 登录成功进行页面跳转
                .and().authorizeRequests()
                .antMatchers("/", "/test", "/login").permitAll() // 不需要进行登录验证的请求
                // 设置当前登录用户对于请求的访问权限
                .antMatchers("/index").hasAnyAuthority("root", "role")
                .anyRequest().authenticated() // 其他请求均需要进行登录验证
                .and().csrf().disable(); // 关闭csrf防护
    }
}

注意:此处无需再重写 configure(AuthenticationManagerBuilder auth) 方法了

之前观看尚硅谷Spring Security 视频时,发现视频中还需要重写此方法

经过本人测试后,发现无需重写也可以,我们只需要编写好自定义的UserDetailsService接口实现类即可。

 

新版本:

Security配置类

@Configuration
public class SecurityConfig{

    /**
     * 创建 BCryptPasswordEncoder 对象,并且将其注入IOC容器中。
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置相关的过滤器链设置,并注入IOC容器中。
     * 旧版本的写法是:继承WebSecurityConfigurerAdapter类,重写它的configure(HttpSecurity http)方法。
     */
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        return http
                .formLogin() // 自定义登陆页面
                .loginPage("/login.html") // 设置登陆页面
                .loginProcessingUrl("/login") // 登录访问路径
                .defaultSuccessUrl("/index").permitAll() // 登录成功进行页面跳转
                .and().authorizeRequests()
                    .antMatchers("/","/test","/login").permitAll() // 不需要进行登录验证的请求
                    // 设置当前登录用户对于请求的访问权限
                    .antMatchers("/index").hasAnyAuthority("root","role")
                .anyRequest().authenticated() // 其他请求均需要进行登录验证
                .and().csrf().disable() // 关闭csrf防护
                .build();
    }
}

新版本中我们无需继承 WebSecurityConfigurerAdapter类 重写它的configure(HttpSecurity http)方法。

而是编写filterChain方法,将之前旧版本中configure(HttpSecurity http)方法中的逻辑写到这里即可。注意:这里需要在最后加上.build(),表示将http创造成SecurityFilterChain!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值