Spring Security配置AuthenticationManager

1. 默认的全局 AuthenticationManager

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
  @Autowired
  public void initialize(AuthenticationManagerBuilder builder) {
    //builder..
  }
}
    • springboot 对 security 进行自动配置时自动在工厂中创建一个全局 AuthenticationManager

    总结

    1. 默认自动配置创建全局 AuthenticationManager 默认找当前项目中是否存在自定义 UserDetailService 实例 自动将当前项目 UserDetailService 实例设置为数据源

    2. 默认自动配置创建全局 AuthenticationManager 在工厂中使用时直接在代码中注入即可

2. 自定义全局 AuthenticationManager

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
  @Override
  public void configure(AuthenticationManagerBuilder builder) {
  	//builder ....
  }
}

总结

  1. 一旦通过 configure 方法自定义 AuthenticationManager 实现 就回将工厂中自动配置 AuthenticationManager 进行覆盖

  2. 一旦通过 configure 方法自定义 AuthenticationManager 实现 需要在实现中指定认证数据源对象 UserDetaiService 实例

  3. 一旦通过 configure 方法自定义 AuthenticationManager 实现 这种方式创建 AuthenticationManager 对象工厂内部本地一个 AuthenticationManager 对象 不允许在其他自定义组件中进行注入

解决方案:在工厂中暴露自定义 AuthenticationManager 实例

默认的AuthenticationManager,在任何地方都可以注入使用,但是这种自定义方式创建的AuthenticationManager是对象工厂内部本地的一个AuthenticationManager,在其他地方使用,比如我们的controller中注入的时候就会出错,需要我们将自定义的AuthenticationManager暴露出去

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
  
    //1.自定义AuthenticationManager  推荐  并没有在工厂中暴露出来
    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        System.out.println("自定义AuthenticationManager: " + builder);
        builder.userDetailsService(userDetailsService());
    }
 
    //作用: 用来将自定义AuthenticationManager在工厂中进行暴露,可以在任何位置注入
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

转载:https://blog.csdn.net/Leon_Jinhai_Sun/article/details/124598340

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值