SpringBoot+Vue implements third-party Weibo login (2)

1. Preparations (official document: address )

The role of this step :

  Before accessing Weibo and logging in, the website needs to first apply to obtain the corresponding appid and appkey, so as to ensure that the website and users can be correctly authenticated and authorized in the subsequent process.

1.1 save appid and appkey

  appid : the unique identifier of the application. In the OAuth2.0 authentication process, the value of appid is the value of oauth_consumer_key.

  appkey : The key corresponding to the appid, which is used to verify the legitimacy of the application when accessing user resources. In the OAuth2.0 authentication process, the value of appkey is the value of oauth_consumer_secret.

2. Place the "Weibo Login" button

The role of this step :

  Place the "Weibo Login" button on the website page, and add the front-end code to the button, so that the Weibo login dialog box will pop up when the button is clicked.

2.1 Request user authorization Token, Oauth2/authorize, return Weibo login address

Request address :

https://api.weibo.com/oauth2/authorize

Request method :

  GET/POST

Request parameters :

required Type and scope illustrate
client_id true string AppKey assigned when applying for an application.
redirect_uri true string Authorize the callback address, the off-site application must be consistent with the set callback address, and the on-site application must fill in the address of the canvas page.
scope false string Parameters required to apply for scope permissions. You can apply for multiple scope permissions at a time, separated by commas. Documentation
state false string It is used to keep the status of the request and the callback. When the callback is made, the parameter will be returned in the Query Parameter. Developers can use this parameter to verify the validity of the request, and can also record the location before the user requests the authorization page. This parameter can be used to prevent cross-site request forgery (CSRF) attacks
display false string The terminal type of the authorization page, see the description below for the value.
forcelogin false boolean Whether to force the user to log in again, true: yes, false: no. The default is false.
language false string Authorization page language, the default is Simplified Chinese, and en is English. In the English version test, any comments from developers can be fed back to @微博API

return data:

return value field Field Type field description
code string It is used in the second step to call the oauth2/access_token interface to obtain the authorized access token.
state string If a parameter is passed, it will be returned.

Return example:

// 请求地址
https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code

// 同意授权后会重定向
http://www.example.com/response&code=CODE

2.2 Download the "Weibo Login" button picture, and place the button at a suitable position on the page

  You can go to the Alibaba Vector Library to download more icons: Alibaba Vector Icon Library  .

2.3 Add the "Weibo Login" button to the foreground code

2.3.1 Effect demonstration

2.3.2 Front-end code (Vue)

  In order to achieve the above effect, the following foreground code should be added to the "Weibo Login" button picture:

<div style="line-height: 22px;margin:0 0 8px 0;color: #9b9b9b;">
        <span style="vertical-align:middle">第三方登录:</span>
        <img :src="qqIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="QQ">
        <img :src="baiduIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="百度">
        <img :src="weiboIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="微博">
        <img :src="zhifubaoIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="支付宝">
        <img :src="giteeIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="Gitee">
        <img :src="githubIcon" width="22" height="22" style="vertical-align:middle;margin-left: 8px" title="GitHub">
</div>

2.3.3 Backend code (Java)

1. Weibo login configuration file information:

# 微博登录配置
weibo.appID = 266666664(替换成你的)
weibo.appKEY = 666666666613a0b31579(替换成你的)
weibo.redirectURI = https://www.youyoushop.work/weiBoCallback(替换成你的)
weibo.authorizeURL = https://api.weibo.com/oauth2/authorize
weibo.accessToken = https://api.weibo.com/oauth2/access_token
weibo.userJson = https://api.weibo.com/2/users/show.json
weibo.revokeoauth = https://api.weibo.com/oauth2/revokeoauth2

2. Read configuration file information constant class:

package com.modules.security.constants;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * 微博登陆常量配置类
 */

@Data
@Configuration
@PropertySource("classpath:thirdparty/config.properties")  // 指定配置文件的路径,属性文件需放在根目录的resources文件夹下面,才能被读取出来
public class WeiBoConstants {

   @Value("${weibo.appID}")
   private String appID;

   @Value("${weibo.appKEY}")
   private String appKEY;

   @Value("${weibo.redirectURI}")
   private String redirectURI;

   @Value("${weibo.authorizeURL}")
   private String authorizeURL;

   @Value("${weibo.accessToken}")
   private String accessToken;

   @Value("${weibo.userJson}")
   private String userJson;

   @Value("${weibo.revokeoauth}")
   private String revokeoauth;

}

3. Conteoller (get the url of Weibo login)

/**
* 获得跳转到微博登录页的url,前台直接a连接访问
*
* @return
* @throws Exception
*/
@LogAnnotation("获得跳转到微博登录页的url")
@ApiOperation("获得跳转到微博登录页的url")
@AnonymousAccess
@GetMapping("/getWeiBoCode")
public ResponseEntity<Object> getWeiBoCode() throws Exception {
    // 授权地址 ,进行Encode转码
    String authorizeURL = weiBoConstants.getAuthorizeURL();

    // 回调地址 ,回调地址要进行Encode转码
    String redirectUri = weiBoConstants.getRedirectURI();

    //用于第三方应用防止CSRF攻击
    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    // 保存到Redis
    redisUtils.set(WEIBOSTATE + "-" + uuid, uuid, expiration, TimeUnit.MINUTES);

    // 拼接url
    StringBuilder url = new StringBuilder();
    url.append(authorizeURL);
    url.append("?client_id=" + weiBoConstants.getAppID());
    url.append("&response_type=code");
    // 转码
    url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirectUri));
    url.append("&state=" + uuid);

    return ResponseEntity.ok(url);
}

3. Get the authorized Access Token

The role of this step :

  Through user authentication login and authorization, Access Token is obtained to prepare for the next step to obtain the user's uid.

  At the same time, Access Token is a parameter that must be passed in when the application calls OpenAPI to access and modify user data.

3.1 Introduction

  That is, the server-side mode is a mode of OAuth2.0 authentication , also known as Web Server Flow.

  Applicable to applications that need to be accessed from a web server, such as Web sites.

3.2 Get Authorization Code (same as 2.1)

Request address :

https://api.weibo.com/oauth2/authorize

Request method :

  GET/POST

Request parameters :

required Type and scope illustrate
client_id true string AppKey assigned when applying for an application.
redirect_uri true string Authorize the callback address, the off-site application must be consistent with the set callback address, and the on-site application must fill in the address of the canvas page.
scope false string Parameters required to apply for scope permissions. You can apply for multiple scope permissions at a time, separated by commas. Documentation
state false string It is used to keep the status of the request and the callback. When the callback is made, the parameter will be returned in the Query Parameter. Developers can use this parameter to verify the validity of the request, and can also record the location before the user requests the authorization page. This parameter can be used to prevent cross-site request forgery (CSRF) attacks
display false string The terminal type of the authorization page, see the description below for the value.
forcelogin false boolean Whether to force the user to log in again, true: yes, false: no. The default is false.
language false string Authorization page language, the default is Simplified Chinese, and en is English. In the English version test, any comments from developers can be fed back to @微博API

Return instructions :

1. If the user successfully logs in and authorizes, it will jump to the specified callback address, and bring the Authorization Code and the original state value after the redirect_uri address. like:

  https://api.weibo.com/oauth2/authorize?code=1E83738E79B0CEBF13FC7C3B094D9B3C&state=cca3c15c527649409cccd889ad2963fe

2. If the user cancels the login process during the login authorization process, for PC websites, the login page will be closed directly.

3.3 Obtain Access Token through Authorization Code

Request address :

https://api.weibo.com/oauth2/access_token

Request method :

  POST

Request parameters :

required Type and scope illustrate
client_id true string AppKey assigned when applying for an application.
client_secret true string AppSecret assigned when applying for an application.
grant_type true string Type of request, fill in authorization_code
code ture string The code value obtained by calling authorize.
rediect_url ture string The callback address must be consistent with the callback address in the registered application.

Return instructions :

return value field Field Type field description
access_token string The only ticket authorized by the user is used to call the open interface of Weibo. It is also the only ticket for the third-party application to verify the login of the Weibo user. The third-party application should use this ticket to establish a unique mapping relationship with the user in its own application to identify the login state, the UID field in this return value cannot be used for login identification.
expires_in string The life cycle of access_token, in seconds.
remind_in string The life cycle of access_token (this parameter will be obsolete soon, developers please use expires_in).
uid string The UID of the authorized user. This field is returned only for the convenience of the developer, reducing one call to the user/show interface. Third-party applications cannot use this field to identify the user's login status. Only the access_token is the only ticket for user authorization.
{
  "access_token":"123123123123",
   "remind_in":"157679999",
   "expires_in":157679999,
   "uid":"123123123",
   "isRealName":"true"
}

4. Instructions for calling OpenAPI to obtain user information

The role of this step :

  After obtaining the Access Token and uid, the user's personal information can be obtained or modified by calling OpenAPI.

Request address :

https://api.weibo.com/2/users/show.json

Request method :

  GET

Request parameters :

required Type and scope illustrate
access_token true string The OAuth authorization method is a required parameter and can be obtained after OAuth authorization.
uid true int64 The ID of the user to be queried.

Return instructions:

private String idstr;                    // 字符串型的用户UID
private String screen_name;              // 用户昵称
private String name;                     // 友好显示名称
private String province;                 // 用户所在省级ID
private String city;                     // 用户所在城市ID
private String location;                 // 用户所在地
private String description;              // 用户个人描述
private String url;                      // 用户博客地址
private String profile_image_url;        // 用户头像地址(中图),50×50像素
private String profile_url;              // 用户的微博统一URL地址
private String domain;                   // 用户的个性化域名
private String weihao;                   // 用户的微号
private String gender;                   // 性别,m:男、f:女、n:未知
private String followers_count;          // 粉丝数
private String friends_count;            // 关注数
private String statuses_count;           // 微博数
private String favourites_count;         // 收藏数
private String created_at;               // 用户创建(注册)时间
private String following;                // 暂未支持
private String allow_all_act_msg;        // 是否允许所有人给我发私信,true:是,false:否
private String geo_enabled;              // 是否允许标识用户的地理位置,true:是,false:否
private String verified;                 // 是否是微博认证用户,即加V用户,true:是,false:否
private String verified_type;            // 是否是微博认证用户,即加V用户,true:是,false:否
private String remark;                   // 用户备注信息,只有在查询用户关系时才返回此字段
private String allow_all_comment;        // 是否允许所有人对我的微博进行评论,true:是,false:否
private String avatar_large;             // 用户头像地址(大图),180×180像素
private String avatar_hd;                // 用户头像地址(高清),高清头像原图
private String verified_reason;          // 认证原因
private String follow_me;                // 该用户是否关注当前登录用户,true:是,false:否
private String online_status;            // 用户的在线状态,0:不在线、1:在线
private String bi_followers_count;       // 用户的互粉数
private String lang;                     // 用户当前的语言版本,zh-cn:简体中文,zh-tw:繁体中文,en:英语

5. Cancel Weibo authorization function

The role of this step :

  Authorization recovery interface to help developers actively cancel the user's authorization. (After the Weibo authorization login is successful, the next time it will automatically log in and skip the authorization, so the authorization will be cleared when the Weibo authorization exits, and the authorization will continue to log in next time)

Request address :

https://api.weibo.com/oauth2/revokeoauth2

Request method :

  GET/POST

Request parameters :

required Type and scope illustrate
access_token true string The OAuth authorization method is a required parameter and can be obtained after OAuth authorization.

Description of usage scenarios

1. When the application is offline, clear the authorization of all users

2. The application has a new function, which needs to obtain the user scope permission, which can be recycled and then redirect the user to authorize

3. Developers need to debug the authorization function repeatedly

4. 应用内实现类似登出微博帐号的功能

6. 测试网站(地址),需要的小伙伴可以测试

6.1 OAuth2.0错误响应中的错误码定义如下表所示:

错误码(error) 错误编号(error_code) 错误描述(error_description)
redirect_uri_mismatch 21322 重定向地址不匹配
invalid_request 21323 请求不合法
invalid_client 21324 client_id或client_secret参数无效
invalid_grant 21325 提供的Access Grant是无效的、过期的或已撤销的
unauthorized_client 21326 客户端没有权限
expired_token 21327 token过期
unsupported_grant_type 21328 不支持的 GrantType
unsupported_response_type 21329 不支持的 ResponseType
access_denied 21330 用户或授权服务器拒绝授予数据访问权限
temporarily_unavailable 21331 服务暂时无法访问
appkey permission denied 21337 应用权限不足

6.2 每个人做的项目需求不同,可能会出现不同的问题,文章仅供参考

6.3 SpringBoot+Vue实现第三方微博登录(一)

6.4 其他第三方登录方式:https://www.cnblogs.com/liyhbk/category/2089783.html

7. 源码购买

7.1 简洁版(淘宝源码

包含登录,第三方登录,跳转首页,SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI等

7.2 Multifunctional version ( Taobao source code )

Including login, registration, third-party login, complete system management module, system tool module, system monitoring module, personal center, etc., SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI, etc.

Guess you like

Origin blog.csdn.net/liyh722/article/details/129611484