Spring Security 的核心组件UserDetailsService(二)

2023-04-15 08:12:10 浏览数 (3)

在SecurityConfig中配置UserDetailsService

在使用UserDetailsService时,我们需要将其配置到SecurityConfig中。在配置中,我们可以指定使用哪个UserDetailsService实现类,并为其指定一个PasswordEncoder对象,用于对密码进行加密。示例如下:

代码语言:javascript复制
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests().antMatchers("/authenticate").permitAll().
                anyRequest().authenticated().and().
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

在上述代码中,我们通过auth对象的userDetailsService()方法将UserDetailsService实现类注入到AuthenticationManagerBuilder中。在这里,我们还通过passwordEncoder()方法为PasswordEncoder对象指定了一个BCryptPasswordEncoder实现类,用于对密码进行加密。

0 人点赞