如何在Spring Security中将电子邮件用作用户名?

时间:2019-04-24 07:59:20

标签: java spring spring-security

我必须从我的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

我也有UserDetailsService的实现,但是在调试时,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"));
    }
}

2 个答案:

答案 0 :(得分:1)

为了实现您的目标,您将必须控制匿名用户的行为。在用户登录之前和何时运行查询时,我都遇到了问题。正如M. Denim所建议的,您应该在此处通过电子邮件进行搜索-> Optional<User> userFromDatabase = userRepository.findOneByEmail(lowercaseLogin); 但是对于getCurrentUserLogin()中的匿名用户,您必须编写一条if语句以返回anonymous@localhost以防userName = anonymousUser

答案 1 :(得分:0)

在这里,我分享了Spring Security Configuration类中的一些代码

.formLogin().loginPage("/login")
.usernameParameter("logInId").passwordParameter("password")

在这里,我使用'logInId'参数登录,而不是使用默认参数。...

我认为您正在搜索类似这样的内容....