举个例子
时间: 2023-08-12 11:21:29 浏览: 56
例子
好的,下面是一个简单的例子:
首先,实现UserDetailsService接口,例如:
```
@Service
public class UserDetailsServiceImpl 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("用户不存在");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
user.isAccountNonLocked(), user.getAuthorities());
}
}
```
在该实现类中,通过UserRepository从数据库中加载用户信息,并转换成UserDetails对象返回。
接着,自定义UserDetails实现类,例如:
```
public class MyUserDetails implements UserDetails {
private String username;
private String password;
public MyUserDetails(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
// 对密码进行加密
return passwordEncoder.encode(password);
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
// 添加一个密码匹配方法
public boolean matchPassword(String rawPassword) {
return passwordEncoder.matches(rawPassword, password);
}
// 添加一个设置密码方法
public void setPassword(String password) {
this.password = password;
}
// 添加一个设置加密器方法
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
}
```
在该类中,实现了UserDetails接口,并添加了一个matchPassword()方法和一个setPassword()方法,用于密码验证和修改密码。在getPassword()方法中,对密码进行了加密操作。
最后,在SecurityConfig中配置自定义的UserDetailsService:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
在该配置类中,调用auth.userDetailsService()方法设置自定义的UserDetailsService,并在该方法中设置密码加密器。这样,当用户登录时,Spring Security就会调用自定义的UserDetailsService加载用户信息,并调用自定义的UserDetails实现类的getPassword()方法进行密码验证。
阅读全文