Kyrylo Lukeniuk
Kyrylo Lukeniuk

Reputation: 397

How to use email as a username in Spring Security?

I have to remove a login field from my User class and use email as a username in SecurityUtils

I've already changed j_username parameter in a frontend, but now the issue remains on a backend

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;
    }

and as a result userName is null, becauseUserDetails and Authentication don't have email. How could I set the field email as a 'j_username'? I've tried this

How to login by email instead of username in spring security

solution but it's not enough since I use an anonymousUser

Also, I have an implementation of UserDetailsService but when debugging it's not called when being the 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"));
    }
}

Upvotes: 2

Views: 2941

Answers (2)

lightning mcqueen
lightning mcqueen

Reputation: 173

In order to achieve your goal you will have to control anonymous user behavior. I had that issue before and when the user is logged in the queries are working fine. As M. Denim suggested you should search by email here -> Optional<User> userFromDatabase = userRepository.findOneByEmail(lowercaseLogin); But in case of anonymous user in getCurrentUserLogin() you have to write an if statement to return anonymous@localhost in case the userName = anonymousUser

Upvotes: 1

Istiaque Hossain
Istiaque Hossain

Reputation: 2367

here i share some code from my Spring Security Configuration class

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

here i use 'logInId' parameter for login instead of default parameter....

i think you searching some thing like this .......

Upvotes: 0

Related Questions