Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log in by email instead of username in Spring security

I use Spring security. Is there a way to log in using email instead of a username in Spring security?

like image 534
abc Avatar asked Jun 04 '18 04:06

abc


2 Answers

You need an "email" parameter in your login form

<input type="email" name="email">

Then let your custom WebSecurityConfigurerAdapter know that "email" is a principal parameter now

protected void configure(HttpSecurity http) throws Exception {
         http
            .formLogin()
            .loginPage("/login")
            .usernameParameter("email")
            .permitAll()
        .and()
            .logout()
            .permitAll();
}

Finally, override loadUserByUsername() in your UserDetailsService implementation

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
    User user = userRepo.findByEmail(email);

    if (user == null) {
        throw new UsernameNotFoundException("Not found!");
    }

    return user;
}
like image 57
Tolik Bugrov Avatar answered Dec 17 '22 06:12

Tolik Bugrov


The simplest way is just regard email as username.

For many cases, email contains your username. For example: [email protected]. In this email, abc is your username.

So you just need to let the user input email directly.

The only thing you need to update is change your query SQL similar as below:

Change (query by username):

SELECT username,password FROM users WHERE username=#{username}

to (query by email)

SELECT email AS username,password FROM users WHERE email=#{username}
like image 45
lucumt Avatar answered Dec 17 '22 04:12

lucumt