我创建了一个密码编码器bean,我只是在UserService -〉createUser()方法中调用了passwordEncoder.encode()方法。但是Spring是如何理解“当登录请求到来时,我必须使用密码编码器”的。我没有在任何地方将passwordEncoder作为参数传递。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
private final JwtFilter jwtFilter;
private final JwtAuthenticationEntryPoint authenticationEntryPoint;
private final JWTAccessDeniedHandler accessDeniedHandler;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(final AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.headers().frameOptions().disable().and()
.csrf().disable()
.cors().and()
.authorizeRequests(auth -> {
auth.antMatchers("/api/admin").hasAuthority("ADMIN");
auth.antMatchers("/api/user").hasAnyAuthority("ADMIN", "USER");
auth.anyRequest().authenticated();
})
.formLogin().disable()
.httpBasic().disable()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) -> web.ignoring().antMatchers("/api/public", "/h2-console/**", "/api/auth/login");
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("*");
}
};
}
}
2条答案
按热度按时间e0uiprwp1#
Spring中的默认密码编码器委托给任何定义的类型为
org.springframework.security.crypto.password.PasswordEncoder
的bean,因此Spring只是委托给您提供的bean。jhdbpxl92#
如果您在这里看到代码
https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfiguration.java#L332
您将看到Spring实际上从当前的
applicationContext
注入beanPasswordEncoder
因此,正如您所看到的,创建此bean是Spring安全在对进入
AuthenticationManager
的密码进行编码时调用的