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

后端 未结 2 546
孤城傲影
孤城傲影 2021-02-04 22:15

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

2条回答
  •  有刺的猬
    2021-02-04 23:04

    You need an "email" parameter in your login form

    
    

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

提交回复
热议问题