要使用Bcrypt自定义密码配置,您可以按照以下步骤进行操作:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
注解启用Web安全性:@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
// 自定义用户服务类(可以是任何实现了UserDetailsService接口的类)
@Autowired
private MyUserDetailsService userDetailsService;
@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("/public").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
UserDetailsService
接口,并重写loadUserByUsername
方法:@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 在这里根据用户名从数据库或其他数据源获取用户信息,并返回UserDetails对象
// 示例代码:
if ("admin".equals(username)) {
return User.builder()
.username("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
} else {
throw new UsernameNotFoundException("User not found with username: " + username);
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在上述代码中,SecurityConfig
类是配置类,它继承自WebSecurityConfigurerAdapter
并重写了configure
方法来配置安全性。MyUserDetailsService
类是自定义的用户服务类,它实现了UserDetailsService
接口,并在loadUserByUsername
方法中返回用户的详细信息。BCryptPasswordEncoder
是Spring Security提供的密码编码器,用于加密和验证密码。
请注意,上述代码中的示例用户信息(用户名和密码)是硬编码的,您应该根据实际情况修改为从数据库或其他数据源获取用户信息。
这是一个基本的示例,您可以根据您的需求进行调整和扩展。