spring-security SpringSecurityPasswordEncoder只需要创建一个bean就可以工作,而不需要在任何方法内部调用

ao218c7q  于 2022-11-11  发布在  Spring
关注(0)|答案(2)|浏览(162)

我创建了一个密码编码器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("*");
        }
    };
}

}

e0uiprwp

e0uiprwp1#

Spring中的默认密码编码器委托给任何定义的类型为org.springframework.security.crypto.password.PasswordEncoder的bean,因此Spring只是委托给您提供的bean。

jhdbpxl9

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注入bean PasswordEncoder
因此,正如您所看到的,创建此bean是Spring安全在对进入AuthenticationManager的密码进行编码时调用的

相关问题