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

1. Preparations

The role of this step :

  Before connecting to Baidu login, the website needs to apply first 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.

1.2 Official development documents

Baidu OAuth Development Documentation

Baidu API documentation description

2. Place the "Baidu Login" button

The role of this step :

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

2.1 Download the "Baidu Login" button image, 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.2 Add the "Baidu Login" button to the page

2.2.1 Effect demonstration

2.2.2 Front-end code (Vue)

  In order to achieve the above effect, the following foreground code should be added to the image of the "Baidu Login" button:

<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.2.3 Backend code (Java)

1. Baidu login profile information:

# 百度登录配置
baidu.appID = 6666666(替换成你的)
baidu.appKEY = 666666666666666666(替换成你的)
baidu.redirectURI = https://www.youyoushop.work/baiDuCallback(替换成你的)
baidu.authorizeURL = https://openapi.baidu.com/oauth/2.0/authorize
baidu.accessToken = https://openapi.baidu.com/oauth/2.0/token
baidu.loggedInUser = https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser
baidu.userInfo = https://openapi.baidu.com/rest/2.0/passport/users/getInfo
baidu.userFriends = https://openapi.baidu.com/rest/2.0/friends/getFriends
baidu.expireSession = https://openapi.baidu.com/rest/2.0/passport/auth/expireSession
baidu.revokeAuthorization = https://openapi.baidu.com/rest/2.0/passport/auth/revokeAuthorization
baidu.image = http://tb.himg.baidu.com/sys/portraitn/item/
baidu.largeImage = http://tb.himg.baidu.com/sys/portrait/item/

2. Read configuration file information constant class:

package com.liyh.constants;

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

/**
 * 百度登陆常量配置类
 *
 * @author Liyh
 */
@Data
@Configuration
@PropertySource("classpath:config.properties")
public class BaiDuConstants {

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

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

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

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

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

    @Value("${baidu.loggedInUser}")
    private String loggedInUser;

    @Value("${baidu.userInfo}")
    private String userInfo;

    @Value("${baidu.userFriends}")
    private String userFriends;

    @Value("${baidu.expireSession}")
    private String expireSession;

    @Value("${baidu.revokeAuthorization}")
    private String revokeAuthorization;

    @Value("${baidu.image}")
    private String image;

    @Value("${baidu.largeImage}")
    private String largeImage;

}

3. Conteoller (get Baidu login url)

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

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

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

    // https://openapi.baidu.com/oauth/2.0/authorize?
    // response_type=code&
    // client_id=Va5yQR666666666666666uXV4&
    // redirect_uri=http%3A%2F%2Fwww.example.com%2Foauth_redirect&
    // scope=email&
    // display=popup

    // 拼接url
    StringBuilder url = new StringBuilder();
    url.append(authorizeURL);
    url.append("?client_id=" + baiDuConstants.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

3.1 Introduction

  The developer server address specified by redirect_uri, after obtaining the authorization code parameter, initiates the following HTTP request from the server to the Baidu Open Platform, and exchanges the code for the web page authorization access_token.

  Note: The length of access_token is reserved for 256 characters.

3.2 Request user authorization and obtain Authorization Code

Request address :

https://openapi.baidu.com/oauth/2.0/authorize

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.
response_type  true string Required parameter, this value is fixed as "code"
scope false string Parameters required to apply for scope permissions. You can apply for multiple scope permissions at a time, separated by commas.
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.

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://openapi.baidu.com/oauth/2.0/authorize?
response_type=code&
    client_id=Va5yQRHlA4Fq4eR3LT0vuXV4&
    redirect_uri=http%3A%2F%2Fwww.example.com%2Foauth_redirect&
    scope=email&
    display=popup

Precautions:

  Each Authorization Code is valid for 10 minutes and can only be used once, and will be invalid if used again.

3.3 Get AccessToken through Authorization Code

Request address :

https://openapi.baidu.com/oauth/2.0/token

Request method :

  POST

Request parameters :

parameter name type Is it necessary describe
grant_type string yes Fixed as authorization_code
code string yes Get the code after user authorization
client_id string yes Application API Key
client_secret string yes Application Secret Key
redirect_uri string yes This value must be consistent with the "redirect_uri" passed when obtaining the Authorization Code.

Return instructions :

return value field Field Type field description
access_token string The obtained web page authorization interface call credentials 
expires_in int The life cycle of access_token, in seconds.
refresh_token string The Refresh Token used to refresh the Access Token, all applications will return this parameter** (valid for 10 years**)
scope  string The final access scope of the Access Token, that is, the list of permissions actually granted by the user (the user may cancel some requested permissions when the user is on the authorization page)
session_key  string The Session Key required for calling the Open API based on http has the same validity period as the Access Token
session_secret string The signature key used to calculate the parameter signature when calling the Open API based on http
{  
     "access_token":  "1.a1231231231231234328",  
     "expires_in":  86400,  
     "refresh_token":  "2.385d55f8615f6666666666c3e39.604800.1293440400-2346678-124328",               
     "scope":  "basic  email",  
     "session_key":  "ANXxSNjwQDu6666666666662bKaXCdlLxn",  
     "session_secret":  "248APxv66666666aK4oZExMB"  
} 

4. Obtain authorized user information

The role of this step :

  After obtaining the access_token, the developer can pull user information through the access_token.

Request address :

https://openapi.baidu.com/rest/2.0/passport/users/getInfo

Request method :

  POST

Request parameters :

required Type and scope illustrate
access_token yes string The OAuth authorization method is a required parameter and can be obtained after OAuth authorization.
get_unionid no int When you need to get unionid, pass get_unionid = 1

Return parameters:

parameter name Parameter Type Is it necessary example value describe
openid string yes oPXyY4O0ZTmUqSX4MRxYDDCccT6Kc9E The unique identifier of a Baidu user, unique to the current developer account and current application
unions string no uA91qQ6gAISTuy0mMqoeh7lZ0w6x478 Baidu user uniform identification, unique to the current developer account
userid uint no 67411167 The unique identifier of the old version of Baidu users, this field will not be returned in the future
securemobile uint no 188888888 The current user binds the mobile phone number (need to apply for permission from the open platform)
username string no t***e The displayed username of the currently logged in user, including the code "*"
portrait string no e2c1776c31393837313031319605 当前登录用户的头像,头像地址拼接使用方法:https://himg.bdimg.com/sys/portrait/item/{$portrait}
userdetail string 喜欢自由 自我简介,可能为空。
birthday string 1987-01-010000-00-00为未知 生日,以yyyy-mm-dd格式显示。
marriage string 0:未知,1:单身,2:已婚3:恋爱4:离异 婚姻状况
sex string 0:未知,1:男,2:女 性别
blood string 0:未知,1:A,2:B,3:O,4:AB,5:其他 血型
is_bind_mobile uint 0:未绑定,1:已绑定 是否绑定手机号
is_realname uint 0:未实名制,1:已实名制 是否实名制

返回值示例:

{    
     "openid": "oPXyY4O0ZTmUqSX4MRxYDDCccT6Kc9E",
     "unionid": "uA91qQ6gAISTuy0mMqoeh7lZ0w6x478",
     "userid": "2097322476",
     "username": "u***9",
     "userdetail": "喜欢自由", 
     "birthday": "1987-01-01",
     "marriage": "0",
     "sex": "1",
     "blood": "3",
     "is_bind_mobile": "1",
     "is_realname": "1" 
}

出错时返回:

{  
     "error_code": "100",  
     "error_msg": "Invalid parameter"   
} 

5. 按需刷新access_token

本步骤的作用

  当access_token过期后,可以使用refresh_token进行刷新。refresh_token有效期为十年。

请求地址

https://openapi.baidu.com/oauth/2.0/token

请求方法

  GET

请求参数

参数名 类型 是否必须 描述
grant_type string 固定为refresh_token
refresh_token string 通过access_token获取到的refresh_token参数
client_id string 应用的API Key
client_secret string 应用的Secret Key

返回参数:

字段名 类型 描述
access_token string 获取到的网页授权接口调用凭证
expires_in int Access Token的有效期,以秒为单位
refresh_token string 用于刷新Access Token的Refresh Token,所有应用都会返回该参数(10年的有效期
scope string The final access scope of the Access Token, that is, the list of permissions actually granted by the user (the user may cancel some requested permissions when the user is on the authorization page)
session_key string The Session Key required for calling OpenAPI based on http has the same validity period as the Access Token
session_secret string The signature key used to calculate the parameter signature when calling OpenAPI based on http.

Example return value:

{  
     "access_token":  "1.a6b1231231231231238",               
     "expires_in":  86400,  
     "refresh_token":  "2.af3d55f8615fdfd9edb7c4b5ebdc3e32.604800.1293440400-2346678-124328",               
     "scope":  "basic  email",  
     "session_key":  "ANXxSNjwQDugf8615OnqeikRMu2bKaXCdlLxn",  
     "session_secret":  "248APxvxjCZ0VEC43EYrvxqaK4oZExMB"  
} 

Returns on error:

{
     "error": "expired_token",
     "error_description": "refresh token has been used"
}

6 Test website ( address ), small partners who need it can test

6.1 Everyone's project needs are different, and different problems may arise. This article is for reference only

6.2 SpringBoot+Vue implements third-party Baidu login (1)

6.3 Other third-party login methods: https://www.cnblogs.com/liyhbk/category/2089783.html

7. Source code purchase

7.1 Concise version ( Taobao source code )

Including login, third-party login, jump homepage, SpringBoot+SpringSecurity+Mysql+Redis+Vue+ElementUI, etc.

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/129875698