是因为用户实体类实现UserDetails这个接口时,我默认把所有抽象方法给自动实现了,而自动生成下面这四个方法,默认返回false,
@Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return false; }问题原因就在这里,只要把它们的返回值改成true就行。
UserDetails 中几个字段的解释:
//返回验证用户密码,无法返回则NULL
String getPassword(); String getUsername();账户是否过期,过期无法验证
boolean isAccountNonExpired();指定用户是否被锁定或者解锁,锁定的用户无法进行身份验证
boolean isAccountNonLocked();指示是否已过期的用户的凭据(密码),过期的凭据防止认证
boolean isCredentialsNonExpired();是否被禁用,禁用的用户不能身份验证
boolean isEnabled();实现接口中loadUserByUsername方法注入数据验证就可以了
自己IUserService用户接口类继承Spring Security提供了 UserDetailsService接口
public interface IUserService extends IService<User>, UserDetailsService { User getUserByUsername(String username); /* *//** * 获取用户所有权限 * * @param username * @return *//* Set<String> getUserPerms(String username);*/ }并且加以实现
@Service @RequiredArgsConstructor @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { private final RoleMapper roleMapper; @Override public User getUserByUsername(String username) { return this.baseMapper.selectOne(new QueryWrapper<User>().lambda() .eq(User::getUsername, username)); } /** * 对用户提供的用户详细信息进行身份验证时 * * @param username * @return * @throws UsernameNotFoundException */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = this.getUserByUsername(username); if (StrUtil.isBlankIfStr(user)) { throw new UsernameNotFoundException("User not found with username: " + username); } //获取用户角色信息 List<Role> roles = roleMapper.findUserRolePermsByUserName(username); user.setRoles(roles); List<String> permList = this.baseMapper.findUserPerms(username); //java8 stream 便利 Set<String> perms = permList.stream().filter(o->StrUtil.isNotBlank(o)).collect(Collectors.toSet()); user.setPerms(perms); //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。 // List<SimpleGrantedAuthority> authorities = new ArrayList<>(); //用于添加用户的权限。只要把用户权限添加到authorities 就万事大吉。 /*for (Role role : roles) { authorities.add(new SimpleGrantedAuthority(role.getRolePerms())); log.info("loadUserByUsername: " + user); }*/ //user.setAuthorities(authorities);//用于登录时 @AuthenticationPrincipal 标签取值 return user; } }自己实现loadUserByUsername从数据库中验证用户名密码,获取用户角色权限信息
拦截器配置