|
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@Component
public class UserService implements UserDetailsService {
// 模拟数据库用户数据
private static Map<String, UserInfo> userMap = new HashMap<>();
@Autowired
private BCryptPasswordEncoder passwordEncoder;
// 初始化加密用户数据
static {
userMap.put("admin", new UserInfo("admin", new BCryptPasswordEncoder().encode("admin")));
userMap.put("user", new UserInfo("user", new BCryptPasswordEncoder().encode("123456")));
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 从数据库查询用户
UserInfo userInfo = userMap.get(username);
if (userInfo == null) {
throw new UsernameNotFoundException("用户名不存在");
}
// 封装权限/角色
ArrayList<GrantedAuthority> authorities = new ArrayList<>();
if ("admin".equals(username)) {
authorities.add(new SimpleGrantedAuthority("add"));
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
// 返回Spring Security规范用户对象
return new User(userInfo.getUsername(), userInfo.getPassword(), authorities);
}
}
// 用户实体类
class UserInfo {
private String username;
private String password;
public UserInfo(String username, String password) {
this.username = username;
this.password = password;
}
// getter/setter
}
|