Spring Security httpbasic的三种密码认证方式
在 Spring Security 中,可以通过多种方式指定密码。以下是几种常见的方式:
认证一—— 在内存中指定密码
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("tom")
.password("{noop}123456") // 指定密码,{noop} 表示密码以明文形式存储
.roles("admin");
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
使用 withUser() 方法指定用户名,使用 password() 方法指定密码。{noop} 前缀表示密码以明文形式存储,仅适用于演示和测试目的。在生产环境中,应该使用适当的密码编码方式。
认证二—— 使用密码编码器(PasswordEncoder)
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private PasswordEncoder passwordEncoder;
@Autowired
public void setPasswordEncoder() {
this.passwordEncoder = new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("tom")
.password(passwordEncoder.encode("123456"))
.roles("admin");
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
通过使用密码编码器(PasswordEncoder),可以对密码进行安全的编码。你可以选择合适的密码编码器实现,例如 BCryptPasswordEncoder、StandardPasswordEncoder、MessageDigestPasswordEncoder 等。需要确保密码编码器的实例已经配置好,并通过 @Autowired 注入到配置类中。
认证三——使用数据库存储密码
spring security 配置类
@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
/**
* 通过使用 UserDetailsService 来加载用户信息,可以从数据库或其他存储中获取用户的密码。
* 你需要实现 UserDetailsService 接口,并根据实际情况从数据库中加载用户信息和密码。
*/
@Autowired
private CustomDetailsService customDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customDetailsService).passwordEncoder(passwordEncoder());
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
自定义 UserDetailsService类
@Service
public class CustomDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 从数据库中根据用户名加载用户信息
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
System.out.println("user=" + user);
return org.springframework.security.core.userdetails.User.builder()
.username(user.getUsername())
.password(user.getPassword())
.roles(user.getRoles())
.build();
}
查询用户密码类
@Repository
public class UserRepository {
public Optional<User> findByUsername(String userName) throws UsernameNotFoundException{
//TODO
//查询数据库用户信息 ....
//tom 123456 admin
return Optional.of(new User("tom","$2a$10$WHv0jAVrVAwde6PaSgD6AeY6MkjweHav1mPm0urIvw4fBnBjfTWau","admin"));
}
}
自定义user类
@Data
@ToString
@AllArgsConstructor
public class User {
private String username;
private String password;
private String roles;
}
使用 UserDetailsService 来加载用户信息,可以从数据库或其他存储中获取用户的密码。你需要实现 UserDetailsService 接口,并根据实际情况从数据库中加载用户信息和密码。
controller类
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "hello word";
}
}
依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.11</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!--添加web依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--添加热部署依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<!--添加lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- <!–添加mp 依赖 –>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>-->
<!--添加Spring Security 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>