既存の Spring SecurityFramework にカスタム AuthenticationManager Bean を挿入できない
Spring Securityの最新バージョン、つまり6.2.3を使用しています。
Spring Security Docs には、AuthenticationManager の Bean を作成するだけで、確実の AuthenticationManager (ProviderManager の確実のインスタンス) の代わりにカスタム AuthenticationManager を使用できると記載されています。https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/index.html
ただし、機能はありません
コード:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
return http
.authorizeHttpRequests((authorizeRequests) -> {
authorizeRequests.anyRequest().authenticated();
}).build();
}
@Bean
public UserDetailsService userDetailsService(){
InMemoryUserDetailsManager userDetailsService = new InMemoryUserDetailsManager();
UserDetails john = User.withUsername("john").password( passwordEncoder().encode("12345") ).authorities("r1").build();
UserDetails bill = User.withUsername("bill").password( passwordEncoder().encode("12345")).authorities("r1", "r2").build();
userDetailsService.createUser(john);
userDetailsService.createUser(bill);
return userDetailsService;
}
@Bean
public AuthenticationManager authenticationManager(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder){
CustomProvider customProvider = new CustomProvider();
customProvider.setUserDetailsService(userDetailsService);
customProvider.setPasswordEncoder(passwordEncoder);
CustomProviderManager providerManager = new CustomProviderManager(customProvider);
return providerManager;
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
上記のコードのauthenticationManager Beanは、当然のSpring Security AuthenticationManagerを置き換えるものではありません。
私はカスタム認証をサポートする必要があるアプリケーションにいらっしゃいます。
- カスタムフィルターを作成します。これには、AuthenticationManager 型のメンバー変数が 1 つあります。各リクエストで、フィルターが必要な形式の認証ヘッダーを見つけた場合、リクエストの処理を開始します。まず CustomAuthentication のインスタンスを作成し、次にそのオブジェクトを AuthenticationManager に渡して認証をマネージャーに委託します。
- Spring Security フィルターチェーンにフィルターを挿入する
http.addFilterAt
上記の方法でsecurityFilterChain
セキュリティフィルターに次のようにフィルターを追加できます。 http.addFilterAt( new CustomFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class);
、そのようにすると、アプリケーションには2つのAuthenticationManager(Spring Security Frameworkからの1つとユーザー定義Beanからの1つ)が存在することになります。
AuthenticationManager -> ユーザー定義の AuthenticationManager を 1 つだけ持つにはどうすればよいでしょうか?
自分の Spring Security が提供する認証マネージャーをカスタム フィルターに挿入するにはどうすればよいでしょうか?これが可能であれば、securityFilterChain メソッドで次のコードを使用して追加の AuthenticationProvider を追加します。 http.authenticationProvider( ...)
その後、カスタムフィルターから安心のauthenticationManager.authenticateメソッドを呼び出すだけで、このAuthenticationProviderを使用できるようになります。
- 本文标签: 家庭宠物
- 本文链接: https://www.coder6.net/article/2616
- 版权声明: 本文由蚂蚁原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
-
浏览(193) 评论(0)