Spring Boot如何实现与微博平台的第三方登录集成?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1356个文字,预计阅读时间需要6分钟。
准备工作+微博开放平台:访问https://open.weibo.com,登录微博开放平台,进入开发者连接,选择网站接入,点击立即接入,填写开发者信息与身份认证信息,创建应用。
准备工作
微博开放平台:open.weibo.com/
网站接入
登陆微博开放平台,进入微连接,选择网站接入
点击立即接入
开发者信息认证
填写开发者信息与身份认证信息
创建应用
开发者信息认证通过后即可创建应用。
应用创建成功后会得到app key和app secret
在应用信息的高级信息中设置授权回调地址
添加测试账号,这里使用开发者账号测试。
流程分析
Web网站的授权流程如下
参考文档:open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6%E8%AF%B4%E6%98%8E
引导授权用户
引导需要授权的用户到如下地址
api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI<a href="api.weibo.com/oauth2/authorize?client_id=123456789&response_type=code&redirect_uri=ws20264753.zicp.fun/weibo/success"> <span>微博</span></a>用户授权
来到授权地址后,需要用户授权,授权成功返回Code码
授权成功
如果用户同意授权,页面跳转至回调地址并携带Code码
换取Access Token
通过授权返回的CODE,请求如下地址,换取Access Token。
api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODEapi.weibo.com/oauth2/access_token?code=0c55753fe19a5bcf0a4a42afd4a64353&grant_type=authorization_code&client_secret=81abcdefghijkmllb4a45f4288ef&redirect_uri=ws20264753.zicp.fun/weibo/success&client_id=231234566得到如下响应结果
body: {"access_token":"2.00123456789480Ngwx8","remind_in":"15896999","expires_in":157679999,"uid":"12345678","isRealName":"true"}HTTP客户端
Code获取后,需要使用Code获取Access Token,以及使用token请求其他接口,此时需要使用发送请求的HTTP客户端,这里使用hutool工具类
发送一个POST请求示例:
//链式构建请求String result2 = HttpRequest.post(url) .header(Header.USER_AGENT, "Hutool api.weibo.com/2/users/show.json").form(selectUserParam).timeout(2000).execute();响应如下类似信息
{ "id": 51234100, "idstr": "58812345464100", "class": 1, "screen_name": "XX", "name": "XX", "province": "51", "city": "14", "location": "四川 成都", "description": "真正的强者,不是流泪的人,而是含泪奔跑的人。", "url": "", "profile_image_url": "tva3.sinaimg.cn/crop.0.0.996.996.50/006qils8jw8f2cztnnp6vj30ro0rpgnj.jpg?KID=imgbed,tva&Expires=1663398489&ssig=JM0ZTUEYbs", "light_ring": false, "cover_image_phone": "ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg", "profile_url": "u/58812345464100", "domain": "", "weihao": "", "gender": "m",}获取用户的粉丝列表
获取用户的粉丝列表接口描述信息如下
Map<String, Object> selectUserParam = new HashMap<>();selectUserParam.put("access_token", weiboUser.getAccess_token());selectUserParam.put("uid", weiboUser.getUid());HttpResponse execute = HttpRequest.get("api.weibo.com/2/friendships/followers.json").form(selectUserParam).timeout(2000).execute();响应结果
粉丝信息: {"users":[],"has_filtered_attentions":false,"next_cursor":600,"previous_cursor":0,"total_number":1789,"use_sink_stragety":false,"has_filtered_fans":true,"use_status_strategy":false,"show_related_topic":false,"display_total_number":1789,"display_total_number_str":"1789","show_unread":false}Spring Boot集成微博登录
添加依赖
添加hutool开发工具包,核心用于发送Http请求。
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.2</version></dependency><!-- thymeleaf页面 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>封装Token等信息
用户授权成功后,使用WeiboUser类封装相关信息
/** * 封装登录认证后的令牌等信息 */@Datapublic class WeiboUser { /** * 令牌 */ private String access_token; /** * 令牌过期时间,该参数即将废弃 */ private String remind_in; /** * 令牌过期时间,单位是秒数 */ private long expires_in; /** * 该社交用户的唯一标识 */ private String uid; /** * 是否记住我 */ private String isRealName;}创建Login页面
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div> <a href="api.weibo.com/oauth2/authorize?client_id=23123456556&response_type=code&redirect_uri=ws20264753.zicp.fun/weibo/success"> <span>微博</span> </a></div></body></html>创建Home页面
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <div> <h3>登录成功</h3> </div></body></html>微博登录逻辑
package com.example.demo.controller;import cn.hutool.ws20264753.zicp.fun/weibo/success"); paramMap.put("code", code); String url = this.buildUrl("api.weibo.com", "/oauth2/access_token", paramMap); //发送post请求换取token HttpResponse api.weibo.com", "/2/users/show.json", selectUserParam); HttpResponse execute = HttpRequest.get("api.weibo.com/2/users/show.json").form(selectUserParam).timeout(2000).execute(); if (execute.getStatus() == 200) { String userInfo = execute.body(); log.info("userInfo: {}", userInfo); //TODO 调用微博api接口获取用户信息,然后进行注册,记录以下值 weiboUser.getAccess_token(); weiboUser.getUid(); weiboUser.getExpires_in(); } } /** * 获取 */ public void getFan(WeiboUser weiboUser) { Map<String, Object> selectUserParam = new HashMap<>(); selectUserParam.put("access_token", weiboUser.getAccess_token()); selectUserParam.put("uid", weiboUser.getUid());// String selectUserUrl = this.buildUrl("api.weibo.com", "/2/users/show.json", selectUserParam); HttpResponse execute = HttpRequest.get("api.weibo.com/2/friendships/followers.json").form(selectUserParam).timeout(2000).execute(); if (execute.getStatus() == 200) { String fanList = execute.body(); log.info("粉丝信息: {}", fanList); } } /** * 构建请求URl地址 * * @return */ private static String buildUrl(String host, String path, Map<String, Object> querys) throws UnsupportedEncodingException { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(host).append(path); StringBuilder sbQuery = new StringBuilder(); for (Map.Entry<String, Object> query : querys.entrySet()) { if (sbQuery.length() > 0) { sbQuery.append("&"); } sbQuery.append(query.getKey()); sbQuery.append("="); sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8")); } if (sbQuery.length() > 0) { sbUrl.append("?").append(sbQuery); } return sbUrl.toString(); }}本文共计1356个文字,预计阅读时间需要6分钟。
准备工作+微博开放平台:访问https://open.weibo.com,登录微博开放平台,进入开发者连接,选择网站接入,点击立即接入,填写开发者信息与身份认证信息,创建应用。
准备工作
微博开放平台:open.weibo.com/
网站接入
登陆微博开放平台,进入微连接,选择网站接入
点击立即接入
开发者信息认证
填写开发者信息与身份认证信息
创建应用
开发者信息认证通过后即可创建应用。
应用创建成功后会得到app key和app secret
在应用信息的高级信息中设置授权回调地址
添加测试账号,这里使用开发者账号测试。
流程分析
Web网站的授权流程如下
参考文档:open.weibo.com/wiki/%E6%8E%88%E6%9D%83%E6%9C%BA%E5%88%B6%E8%AF%B4%E6%98%8E
引导授权用户
引导需要授权的用户到如下地址
api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI<a href="api.weibo.com/oauth2/authorize?client_id=123456789&response_type=code&redirect_uri=ws20264753.zicp.fun/weibo/success"> <span>微博</span></a>用户授权
来到授权地址后,需要用户授权,授权成功返回Code码
授权成功
如果用户同意授权,页面跳转至回调地址并携带Code码
换取Access Token
通过授权返回的CODE,请求如下地址,换取Access Token。
api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODEapi.weibo.com/oauth2/access_token?code=0c55753fe19a5bcf0a4a42afd4a64353&grant_type=authorization_code&client_secret=81abcdefghijkmllb4a45f4288ef&redirect_uri=ws20264753.zicp.fun/weibo/success&client_id=231234566得到如下响应结果
body: {"access_token":"2.00123456789480Ngwx8","remind_in":"15896999","expires_in":157679999,"uid":"12345678","isRealName":"true"}HTTP客户端
Code获取后,需要使用Code获取Access Token,以及使用token请求其他接口,此时需要使用发送请求的HTTP客户端,这里使用hutool工具类
发送一个POST请求示例:
//链式构建请求String result2 = HttpRequest.post(url) .header(Header.USER_AGENT, "Hutool api.weibo.com/2/users/show.json").form(selectUserParam).timeout(2000).execute();响应如下类似信息
{ "id": 51234100, "idstr": "58812345464100", "class": 1, "screen_name": "XX", "name": "XX", "province": "51", "city": "14", "location": "四川 成都", "description": "真正的强者,不是流泪的人,而是含泪奔跑的人。", "url": "", "profile_image_url": "tva3.sinaimg.cn/crop.0.0.996.996.50/006qils8jw8f2cztnnp6vj30ro0rpgnj.jpg?KID=imgbed,tva&Expires=1663398489&ssig=JM0ZTUEYbs", "light_ring": false, "cover_image_phone": "ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg", "profile_url": "u/58812345464100", "domain": "", "weihao": "", "gender": "m",}获取用户的粉丝列表
获取用户的粉丝列表接口描述信息如下
Map<String, Object> selectUserParam = new HashMap<>();selectUserParam.put("access_token", weiboUser.getAccess_token());selectUserParam.put("uid", weiboUser.getUid());HttpResponse execute = HttpRequest.get("api.weibo.com/2/friendships/followers.json").form(selectUserParam).timeout(2000).execute();响应结果
粉丝信息: {"users":[],"has_filtered_attentions":false,"next_cursor":600,"previous_cursor":0,"total_number":1789,"use_sink_stragety":false,"has_filtered_fans":true,"use_status_strategy":false,"show_related_topic":false,"display_total_number":1789,"display_total_number_str":"1789","show_unread":false}Spring Boot集成微博登录
添加依赖
添加hutool开发工具包,核心用于发送Http请求。
<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.2</version></dependency><!-- thymeleaf页面 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>封装Token等信息
用户授权成功后,使用WeiboUser类封装相关信息
/** * 封装登录认证后的令牌等信息 */@Datapublic class WeiboUser { /** * 令牌 */ private String access_token; /** * 令牌过期时间,该参数即将废弃 */ private String remind_in; /** * 令牌过期时间,单位是秒数 */ private long expires_in; /** * 该社交用户的唯一标识 */ private String uid; /** * 是否记住我 */ private String isRealName;}
