开源项目ruoyi-vue多类型账户登录的一种实现方式

111 阅读1分钟

新增CustomAuthenticationToken

public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken {

    private String additionalParameter;

    public CustomAuthenticationToken(Object principal, Object credentials, String additionalParameter) {
        super(principal, credentials);
        this.additionalParameter = additionalParameter;
    }

    public String getAdditionalParameter() {
        return additionalParameter;
    }
}

SysLoginService中CustomAuthenticationToken代替UsernamePasswordAuthenticationToken

// 登录前置校验
loginPreCheck(username, password);
// 用户验证
Authentication authentication = null;
try {
    CustomAuthenticationToken authenticationToken = new CustomAuthenticationToken(username, password, userType);
    AuthenticationContextHolder.setContext(authenticationToken);
    // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
    authentication = authenticationManager.authenticate(authenticationToken);
} catch (Exception e) {

UserDetailsServiceImpl.loadUserByUsername中获取使用userType

String userType = ((CustomAuthenticationToken) usernamePasswordAuthenticationToken).getAdditionalParameter();