springboot重写security 密码验证
时间: 2023-07-08 20:11:32 浏览: 123
spring boot实现验证码功能
要重写Spring Security的密码验证,可以通过实现`UserDetailsService`接口来自定义用户验证逻辑。具体步骤如下:
1. 创建一个实现`UserDetailsService`接口的类,例如`CustomUserDetailsService`,并重写`loadUserByUsername`方法。
```java
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found with username: " + username);
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
getAuthorities(user));
}
private Collection<? extends GrantedAuthority> getAuthorities(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role : user.getRoles()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
return authorities;
}
}
```
2. 在Spring Security配置类中,使用`CustomUserDetailsService`代替默认的`InMemoryUserDetailsManager`。
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER")
.and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在以上代码中,我们将`CustomUserDetailsService`注入到了`AuthenticationManagerBuilder`中,并使用`BCryptPasswordEncoder`加密密码。这样,当用户登录时,Spring Security会调用`CustomUserDetailsService`中的`loadUserByUsername`方法来验证用户的用户名和密码。
注意,我们还需要在数据库中存储加密过的密码,并在`User`实体类中添加一个密码字段,例如:
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@ManyToMany(fetch = FetchType.EAGER)
private Set<Role> roles = new HashSet<>();
// getters and setters
}
```
阅读全文