Home > Software engineering >  Spring Security Password Encoder is working just by creating a bean and without calling inside any m
Spring Security Password Encoder is working just by creating a bean and without calling inside any m

Time:09-27

I created a password encoder bean and I am just calling passwordEncoder.encode() method in UserService -> createUser() method. But how spring is understanding that "I have to use password encoder when login request came". I am not passing passwordEncoder as an argument anywhere.

@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("*");
        }
    };
}

}

CodePudding user response:

The default password encoder in Spring delegates to any defined beans of type org.springframework.security.crypto.password.PasswordEncoder. So Spring is simply delegating to the bean that you provided.

CodePudding user response:

If you see the code here

https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/annotation/authentication/configuration/AuthenticationConfiguration.java#L332

You would see that Spring actually injects the bean PasswordEncoder from the current applicationContext

So as you see creating this bean is what the Spring security calls when encoding the password coming into the AuthenticationManager

  • Related