gpt4 book ai didi

java - 如何在 Spring Security 中使用电子邮件作为用户名?

转载 作者:行者123 更新时间:2023-11-30 05:40:06 24 4
gpt4 key购买 nike

我必须从我的 User 类中删除登录字段,并使用 email 作为 SecurityUtils 中的用户名

我已经更改了前端中的 j_username 参数,但现在问题仍然存在于后端

public static String getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String userName = null;
if (authentication != null) {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
userName = springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
userName = (String) authentication.getPrincipal();
}
}
return userName;
}

结果userName为空,因为UserDetailsAuthentication没有电子邮件。如何将字段 email 设置为“j_username”?我已经尝试过了

How to login by email instead of username in spring security

解决方案,但这还不够,因为我使用anonymousUser

另外,我有一个 UserDetailsS​​ervice 的实现,但在调试时,作为 anonymousUser 时不会调用它

public class DomainUserDetailsService implements UserDetailsService {


private final UserRepository userRepository;

public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}

@Override
public UserDetails loadUserByUsername(final String login) {
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
Optional<User> userFromDatabase = userRepository.findOneByLogin(lowercaseLogin);
return userFromDatabase.map(user -> {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(lowercaseLogin,
user.getPassword(),
grantedAuthorities);
}).orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " +
"database"));
}
}

最佳答案

为了实现您的目标,您必须控制匿名用户的行为。我之前遇到过这个问题,当用户登录时查询工作正常。正如 M. Denim 建议您应该在此处通过电子邮件搜索 -> Optional<User> userFromDatabase = userRepository.findOneByEmail(lowercaseLogin);
但如果是getCurrentUserLogin()中的匿名用户你必须编写一个 if 语句来返回 anonymous@localhost如果userName = anonymousUser

关于java - 如何在 Spring Security 中使用电子邮件作为用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55825059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com