全新版本Spring Security,这样用才够优雅

前不久Spring Boot 2.7.0 刚刚发布,Spring Security 也升级到了5.7.1 。升级后发现,原来一直在用的Spring Security配置方法,居然已经被弃用了。不禁感慨技术更新真快,用着用着就被弃用了!今天带大家体验下Spring Security的最新用法,看看是不是够优雅!

SpringBoot实战电商项目mall(50k+star)地址:github.com/macrozheng/…

基本使用

我们先对比下Spring Security提供的基本功能登录认证,来看看新版用法是不是更好。

升级版本

首先修改项目的pom.xml文件,把Spring Boot版本升级至2.7.0版本。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.0</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

旧用法

在Spring Boot 2.7.0 之前的版本中,我们需要写个配置类继承
WebSecurityConfigurerAdapter,然后重写Adapter中的三个方法进行配置;

/**
 * SpringSecurity的配置
 * Created by macro on 2018/4/26.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OldSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UmsAdminService adminService;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //省略HttpSecurity的配置
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

如果你在SpringBoot 2.7.0版本中进行使用的话,你就会发现
WebSecurityConfigurerAdapter已经被弃用了,看样子Spring Security要坚决放弃这种用法了!

新用法

新用法非常简单,无需再继承
WebSecurityConfigurerAdapter,只需直接声明配置类,再配置一个生成SecurityFilterChainBean的方法,把原来的HttpSecurity配置移动到该方法中即可。

/**
 * SpringSecurity 5.4.x以上新用法配置
 * 为避免循环依赖,仅用于配置HttpSecurity
 * Created by macro on 2022/5/19.
 */
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        //省略HttpSecurity的配置
        return httpSecurity.build();
    }

}

新用法感觉非常简洁干脆,避免了继承
WebSecurityConfigurerAdapter并重写方法的操作,强烈建议大家更新一波!

高级使用

升级 Spring Boot 2.7.0版本后,Spring Security对于配置方法有了大的更改,那么其他使用有没有影响呢?其实是没啥影响的,这里再聊聊如何使用Spring Security实现动态权限控制!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值