Spring Cloud OAuth2(二) 扩展登陆方式:账户密码登陆、 手机验证码登陆、 二维码扫码登陆

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_world!

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值