AuthenticationManagerBuilder

AuthenticationManagerBuilder

我已经设置了样板弹簧安全配置器:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


@Autowired
private DataSource datasource;

@Override
protected void configure(HttpSecurity http) throws Exception {
   // ...setting up security for routes, etc.
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      // here I have access to the AuthenticationManagerBuilder
      // I can associate it with my datasource, set the password encoder, etc.
 JdbcUserDetailsManager userDetailsService = new   JdbcUserDetailsManager();
    userDetailsService.setDataSource(datasource);
    PasswordEncoder encoder = new BCryptPasswordEncoder();
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    auth.jdbcAuthentication().dataSource(datasource);

}


但是我想要的是能够像这样从另一个bean访问AuthenticationManagerBuilder:

@Service
public class MyUserService {

@Autowired
AuthenticationManagerBuilder builder;

public void createUser(...) {
//use builder here...
    JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager();
    userDetailsService.setDataSource(datasource);
    PasswordEncoder encoder = new BCryptPasswordEncoder();
    builder.userDetailsService(userDetailsService)
      .passwordEncoder(encoder);
    builder.jdbcAuthentication().dataSource(datasource);
    userDetailsService.createUser(new User(...));
}


有没有办法从其他bean访问自动传递给AuthenticationManagerBuilder方法的同一configure()实例?

最佳答案

AuthenticationManagerBuilder实际上仅用于构建身份验证对象(即UserDetails,AuthenticationProvider,AuthenticationManager)。它不打算在应用程序本身中使用。

相反,我建议使用UserDetailsManager API。您可以创建一个UserDetailsManager Bean,将UserDetailsManager提供给AuthenticationManagerBuilder来创建AuthenticationProvider和AuthenticationManager,然后可以在代码内直接使用UserDetailsManager。

像这样:

@EnableWebMvcSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    ...

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth, UserDetailsService uds) throws Exception {
      auth
        .userDetailsService(uds)
        .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Bean
    public UserDetailsManager udm(DataSource dataSource) {
        JdbcUserDetailsManager udm = new JdbcUserDetailsManager();
        udm.setDataSource(dataSource);
        return udm;
    }
}

@Service
public class MyUserService {

    @Autowired
    UserDetailsManager udm;

    public void createUser(...) {
        //use builder here...
        udm.createUser(new User(...));
    }
}


需要注意的一件事是,我们利用了AuthenticationManagerBuilder的全局实例。为了确保在构建AuthenticationProvider和AuthenticationManager之前调用configureGlobal方法,您需要在Configuration类上具有EnableGlobalAuthentication,EnableWebMvcSecurity或EnableWebSecurity批注(我们的示例已经做到了)。

08-28 01:50