userdetailsservice用户名是否必须与合同规定的userdetails用户名相同?

des4xlb0  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(389)
public interface UserDetailsService {
/**
 * Locates the user based on the username. In the actual implementation, the search
 * may possibly be case sensitive, or case insensitive depending on how the
 * implementation instance is configured. In this case, the <code>UserDetails</code>
 * object that comes back may have a username that is of a different case than what
 * was actually requested..
 * @param username the username identifying the user whose data is required.
 * @return a fully populated user record (never <code>null</code>)
 * @throws UsernameNotFoundException if the user could not be found or the user has no
 * GrantedAuthority
 */
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;}

loaduserbyusername参数是username

public interface UserDetails extends Serializable {
/**
 * Returns the username used to authenticate the user. Cannot return
 * <code>null</code>.
 * @return the username (never <code>null</code>)
 */
String getUsername()}

getusername返回用户名
这个用户名在两个by interface contract中必须是相同的值吗?例如我想要 loadUserByUsername(String username) 用户名可以是电子邮件 String getUsername() 必须是用户ID。通过电子邮件加载,但返回用户名为userid的userdetails。

s8vozzvw

s8vozzvw1#

你不能,如果你按用户名加载用户,你将按用户名从数据库中搜索它。

hi3rlvi2

hi3rlvi22#

我是这样实现的:
https://docs.spring.io/spring-security/site/docs/5.4.1/reference/html5/#servlet-身份验证jdbc
appuserservices类

@Service
public class AppUserServices implements AppUserService{

@Autowired
    private AppUserRepository repo;

    @Override
    public AppUser fetchByUsername(String username) {
        return repo.findByUsername(username);
    }

    @Override
    public void persist(AppUser appUser) {
        repo.save(appUser);     
    }

 }

appuserdetailservices类

@Service
public class AppUserDetailServices implements UserDetailsService{

@Autowired
private AppUserService service;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    Optional<AppUser> user = Optional.ofNullable(service.fetchByUsername(username));

    if(user.isPresent()) {
        User  dbuser = new User(
                user.get().getUsername(),
                user.get().getPassword(),
                user.get().getAuthorities());
        return dbuser;
    } else {
        throw new UsernameNotFoundException(username);

    }
}

}

相关问题