https://www.cnblogs.com/fp2952/p/9193959.html
概要
基于上文讲解的spring cloud 授权服务的搭建,本文扩展了spring security 的登陆方式,增加手机验证码登陆、二维码登陆。 主要实现方式为使用自定义filter、 AuthenticationProvider、 AbstractAuthenticationToken 根据不同登陆方式分别处理。 本文相应代码在Github上已更新。
GitHub 地址:https://github.com/fp2952/spring-cloud-base/tree/master/auth-center/auth-center-provider
srping security 登陆流程
关于二维码登陆
二维码扫码登陆前提是已在微信端登陆,流程如下:
- 用户点击二维码登陆,调用后台接口生成二维码(带参数key), 返回二维码链接、key到页面
- 页面显示二维码,提示扫码,并通过此key建立websocket
- 用户扫码,获取参数key,点击登陆调用后台并传递key
- 后台根据微信端用户登陆状态拿到userdetail, 并在缓存(redis)中维护 key: userDetail 关联关系
- 后台根据websocket: key通知对于前台页面登陆
- 页面用此key登陆
最后一步用户通过key登陆就是本文的二维码扫码登陆部分,实际过程中注意二维码超时,redis超时等处理
自定义LoginFilter
自定义过滤器,实现AbstractAuthenticationProcessingFilter,在attemptAuthentication方法中根据不同登陆类型获取对于参数、 并生成自定义的 MyAuthenticationToken。
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
// 登陆类型:user:用户密码登陆;phone:手机验证码登陆;qr:二维码扫码登陆
String type = obtainParameter(request, "type");
String mobile = obtainParameter(request, "mobile");
MyAuthenticationToken authRequest;
String principal;
String credentials;
// 手机验证码登陆
if("phone".equals(type)){
principal = obtainParameter(request, "phone");
credentials = obtainParameter(request, "verifyCode");
}
// 二维码扫码登陆
else if("qr".equals(type)){
principal = obtainParameter(request, "qrCode");
credentials = null;
}
// 账号密码登陆
else {
principal = obtainParameter(request, "username");
credentials = obtainParameter(request, "password");
if(type == null)
type = "user";
}
if (principal == null) {
principal = "";
}
if (credentials == null) {
credentials = "";
}
principal = principal.trim();
authRequest = new MyAuthenticationToken(
principal, credentials, type, mobile);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authReques