spring-security 如何使用用户名或邮箱登录

发布时间 2023-05-23 23:59:07作者: pmh905001

这面文章是介绍使用邮箱以及验证码登录的方式,如果变成如下这种通过用户名或者邮箱的登录方式呢?

spring-security只实现用了用户名+密码登录,没有邮箱+密码登录的方式该怎么进行扩展呢?

 

实际做法如下:

在spring-security.xml添加一个能够支持邮箱登录的bean,并且注入到:authentication-manager 下的 authentication-provider 


    <beans:bean id="userDetailsManager" class="com.hyxc.moikiitos.services.UserDetailsServiceImpl">
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsManager">
            <password-encoder ref="encoder" />
        </authentication-provider>
    </authentication-manager>

 

剩下的事情就是扩展 JdbcUserDetailsManager,只需要覆盖 loadUsersByUsername(String username)方法,让email字段也能作为查询条件即可。代码如下:

package com.hyxc.moikiitos.services;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.JdbcUserDetailsManager;

public class UserDetailsServiceImpl extends JdbcUserDetailsManager {
    @Override
    protected List<UserDetails> loadUsersByUsername(String username) {
        return getJdbcTemplate().query("select username,password,enabled from users where username = ? or email = ?",
                new String[] { username, username }, new RowMapper<UserDetails>() {
                    public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
                        String username = rs.getString(1);
                        String password = rs.getString(2);
                        boolean enabled = rs.getBoolean(3);
                        return new User(username, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES);
                    }

                });

    }

}