实战授权码登录流程

我是经常阅读公众号优质文章,也经常体验到公众号的授权登录功能。今天就来实现下,流程图如下

效果图

后端接口

主要用来接收微信服务器推送的公众号用户触发的事件、生成和验证授权码的有效性

解析微信服务器推送的事件通知

java 复制代码
public String login(ServletRequest request, @RequestBody(required = false) String body){
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String[] value = stringEntry.getValue();
            System.out.println(stringEntry.getKey()+" >> ");
            for (int i = 0; i < value.length; i++) {
                System.out.println(value[i]);
            }
        }
        System.out.println(body);
        WxMessage wxMessage = ParseWxMessage.parse(body);
        if(wxMessage == null && request.getParameter("echostr") != null){
            return request.getParameter("echostr");
        }
        String text = "你好";
        switch (wxMessage.getContent()){
            case "xxx":
                text = "";
                break;

            default:
                // 用户已回复
                AccessCodeUtils.commit(wxMessage.getContent());
                if (wxMessage.getContent().length() == 6 && AccessCodeUtils.check(wxMessage.getContent())){
                    text = "恭喜你已经解锁diyai全部文章";
                }
                break;
        }
        return ParseWxMessage.response(wxMessage.getFromUserName(),text);
    }

生成和验证授权码的有效性

java 复制代码
public class BlogController {
    @RequestMapping("/checkAccessCode")
    // 服务器配置
    public void checkAccessCode(ServletRequest request, @RequestParam("token") String token, ServletResponse response) {
        String res = "ok";
        if (AccessCodeUtils.check(token)) {
            // 清理缓存
            AccessCodeUtils.remove(token);
        }else{
            res = "refuse";
        }
        System.out.println("token " + token);
        try {
            response.getWriter().write(res);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @RequestMapping("/getAccessCode")
    // 服务器配置
    public void getAccessCode(ServletRequest request, ServletResponse response) {
        String code = UUID.randomUUID().toString().substring(0, 6).toUpperCase();
        AccessCodeUtils.create(code);
        try {
            response.getWriter().write(code);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

前端弹窗验证

访问链接时先验证本地的授权码是否有效,如果没有,则弹出授权弹窗,验证通过后才关闭弹窗,同时将验证信息保存到cookie中,并设定好过期时间

js 复制代码
     mounted: function () {
         console.log("lock article")
         // 本地服务不验证
         if(location.href.includes("localhost") || location.href.startsWith("http://192.168")){
             return;
         }
         // 定时任务
         this.interval = setInterval(() => {
             const lock = this.getCookie("_unlock")
             if(lock == 'success'){
                 clearInterval(this.interval)
                 this.show = false;
                 return
             }
             this.show = true
             console.log("is lock",lock,this.getCookie("_unlock"))
             if(this.accessCode == ''){
                 this.getToken()
             }

             if (!lock) {
                 this.checkAccessCode()
             }
         }, 1500);
     },
     methods: {
         isLock() {
             console.log(this.$page.frontmatter.lock)
             return "need" === this.$page.frontmatter.lock;
         },
         checkAccessCode: function () {
             let res = this.getCookie("_unlock");
             if ('success' === res) {
                 clearInterval(this.interval)
                 this.show = false;
                 return;
             }
             const that = this
             $.ajax({
                     url: 'xxxxx/checkAccessCode', // 填写自己的url
                     type: "GET",
                     dataType: "text",
                     data: {
                         token: this.accessCode
                     },
                     success: function (data) {
                         console.log("check res",data)
                         if (data === 'ok') {
                             that.setCookie("_unlock", "success", 24*30);
                         }
                     },
                     error: function (data) {
                         // that.show = false;
                     }
                 })
         },

         getCode(){
             const that = this
             $.ajax({
                     url: 'xxxxx/getAccessCode', // 填写自己的url
                     type: "GET",
                     dataType: "text",
                     data: {},
                     success: function (data) {
                         console.log("get access code:",data)
                         that.accessCode  = data
                     },
                     error: function (data) {
                         // that.setCookie("_unlock", "success", 7);
                     }
                 })
         },
         getToken: async function () {
			return "" // 自己定制
		}
         getCookie: function (name) {
             let value = "; " + document.cookie;
             let parts = value.split("; " + name + "=");
             if (parts.length === 2)
                 return parts.pop().split(";").shift();
         },
         setCookie: function (name, value, hours){
             let exp = new Date();
             exp.setTime(exp.getTime() + hours*60*60*1000);
             // ;path=/ cookie全站有效
             document.cookie = name + "="+ escape (value) + ";path=/;expires=" + exp.toGMTString();
         }
     }
相关推荐
l软件定制开发工作室2 分钟前
Spring开发系列教程(32)——Spring Boot开发
java·spring boot·后端·spring
DolphinScheduler社区6 分钟前
Apache DolphinScheduler 3.4.1 发布,新增任务分发超时检测
java·数据库·开源·apache·海豚调度·大数据工作流调度
黑眼圈子10 分钟前
Java正则表达式基础知识
java·开发语言·正则表达式
iPadiPhone11 分钟前
性能优化的“快车道”:Spring @Async 注解深度原理与大厂实战
java·后端·spring·面试·性能优化
彭于晏Yan11 分钟前
JsonProperty注解的access属性
java·spring boot
Mr.朱鹏17 分钟前
分布式-redis集群架构
java·redis·分布式·后端·spring·缓存·架构
予枫的编程笔记18 分钟前
【面试专栏|Java并发编程】Java并发锁对比:synchronized与Lock,底层原理+适用场景详解
java·synchronized·java面试·java并发编程·并发锁·面试干货·lock接口
醇氧19 分钟前
PowerPoint 批量转换为 PDF
java·spring boot·spring·pdf·powerpoint
java1234_小锋20 分钟前
Java高频面试题:RabbitMQ如何实现消息的持久化?
java·开发语言
爱打代码的小林28 分钟前
用 LangChain 解析大模型输出
java·python·langchain·大模型