Spring Security简单增加短信验证码登录

查网上资料增加短信验证码登录都要增加一大推,要重头写Spring Security的实现,我呢,只想在原来的密码登录基础上简单实现一下短信验证码登录。
1、首先得先一个认证类,来认证验证码是否正确,这个类要实现Spring Security提供的AuthenticationProvider接口
2、其次需要一个认证令牌的类,作为你的认证信息,这个类要继承Spring Security提供的AbstractAuthenticationToken抽象类
3、然后要把你的认证类加到spring security配置中,就是继承WebSecurityConfigurerAdapter的类
4、最后就是登陆时调用Spring Security的认证了
上代码:
1、认证类

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class SmsAuthenticationProvider implements AuthenticationProvider {

	//用户验证处理 实现Spring Security提供的UserDetailsService的类 下面会给这个类
	private UserDetailsServiceImpl userDetailsServiceImpl;
	//redis缓存 用你的缓存就行 这个就不给了 用来存放验证码的
    private RedisCache redisCache;

    public SmsAuthenticationProvider(@Qualifier("userDetailsServiceImpl") UserDetailsServiceImpl smsUserDetailsServiceImpl, RedisCache redisCache) {
        this.userDetailsServiceImpl = smsUserDetailsServiceImpl;
        this.redisCache = redisCache;
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    	SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;
        Object principal = authentication.getPrincipal();// 获取凭证也就是用户的手机号
        String phone = "";
        if (principal instanceof String) {
            phone = (String) principal;
        }
        
        String inputCode = (String) authentication.getCredentials(); // 获取输入的验证码
        
        Integer cacheObject = redisCache.getCacheObject("login"+phone);
    	
        // 1. 检验Redis手机号的验证码
        if (cacheObject == null) {
            throw new BadCredentialsException("验证码已经过期或尚未发送,请重新发送验证码");
        }
        if (!inputCode.equals(cacheObject+"")) {
            throw new BadCredentialsException("输入的验证码不正确,请重新输入");
        }
        // 2. 根据手机号查询用户信息
        UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(phone);
        if (userDetails == null) {
            throw new InternalAuthenticationServiceException("phone用户不存在,请注册");
        }
         // 3. 重新创建已认证对象,
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, inputCode, userDetails.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

UserDetailsServiceImpl类 这里面的东西就不固定了 想咋写就咋写 主要是loadUserByUsername方法 这个必须有 返回的UserDetails(Spring Security提供的用来存放用户信息的类,你可以随便写个类实现这个类,然后你就可以存放你自己要用的信息了)loadUserByUsername这个方法会在调用Spring Security的认证时用 我会在代码中表明在哪块会调用到这个类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserNameOrPhone(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户:{} 不存在.", username);
            throw new ServiceException("登录用户:" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户:{} 已被删除.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户:{} 已被停用.", username);
            throw new ServiceException("对不起,您的账号:" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user.getClinicId(), user, permissionService.getMenuPermission(user));
    }
}

2、存放认证令牌


import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;

import java.util.Collection;

public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
    
    private final Object principal; //存放认证信息,认证之前存放手机号,认证之后存放登录的用户
    private Object credentials;

    public SmsCodeAuthenticationToken(String mobile, Object credentials) {
        super(null);
        this.principal = mobile;
        this.credentials = credentials;
        this.setAuthenticated(false);
    }

    public SmsCodeAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true);
    }

    public Object getCredentials() {
    	return this.credentials;
    }

    public Object getPrincipal() {
        return this.principal;
    }

    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        if (isAuthenticated) {
            throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        } else {
            super.setAuthenticated(false);
        }
    }

    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }
}

3、spring security配置
在这里插入图片描述
在这里插入图片描述
4、登录调用认证

/**
     * 验证码登录
     * 
     * @param username 用户名
     * @param code 验证码
     * @return 结果
     */
    public String loginSms(String phone, String smsCode)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername(这块调用了UserDetailsServiceImpl的loadUserByUsername)
            authentication = authenticationManager
                    .authenticate(new SmsCodeAuthenticationToken(phone, smsCode));
        }
        catch (Exception e)
        {
            if (e instanceof BadCredentialsException)
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, null,Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, null,Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, loginUser.getClinicId(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        //上面已经结束了 剩下交给你自己了
        recordLoginInfo(loginUser.getUserId());
        // 生成token 这块你们根据你们的业务自己写了 tokenService.createToken使我们的业务方法
        return tokenService.createToken(loginUser);
    }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值