SpringBoot+Vue enables third-party microblog login

one   preparation

The purpose of this step:

Before logging in to the microblog, the website needs to apply and obtain the corresponding appid and appkey to ensure that the website and users can be verified and authorized correctly in the subsequent process.

1.1 save appid and appkey

Appid: the unique ID of the application. During OAuth 2.0 authentication, the value of appid is OAuth_ consumer_ The value of the key.

Appkey: the key corresponding to appid, which is used to verify the legitimacy of the application when accessing user resources. During OAuth 2.0 authentication, the value of appkey is OAuth_ consumer_ Value of secret.

two   Place the "microblog login" button

The purpose of this step:

Place the "microblog login" button on the website page, and add the foreground code for the button to realize that clicking the button will pop up the microblog login dialog box.

two point one   Request user authorization Token, Oauth2/authorize

Request address:

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

Request method:

  GET/POST

Request parameters:

 Mandatory Type and scopeexplain
client_id true string AppKey assigned when applying for application.
redirect_uri true string For the authorized callback address, the off-site application shall be consistent with the set callback address, and the on-site application shall fill in the address of canvas page.
scope false string Parameters required to apply for scope permissions. You can apply for multiple scope permissions at one time, separated by commas. Working with documents
state false string It is used to maintain the status of request and callback. During callback, the parameter will be returned in Query Parameter. The developer can use this parameter to verify the validity of the request, and can also record the position 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 following description for the value.
forcelogin false boolean Whether to force users to log in again. true: Yes, false: No. The default is false.
language false string The language of the authorization page is simplified Chinese by default, and en is English. In the English version of the test, any comments of the developer can be fed back to @ microblog API

Return data:

Return value fieldField typeField description
code string Used to call oauth2 / access in the second step_ Token interface to obtain the access token after authorization.
state string If you pass a parameter, it will be returned.

Return example:

  // Request address
  https://api.weibo.com/oauth2/authorize?client_id=123050457758183&redirect_uri=http://www.example.com/response&response_type=code

  // Redirect when authorization is granted
  http://www.example.com/response&code=CODE

two point two   Download the "microblog login" button image and place the button in the appropriate position on the page

You can download more icons from Ali vector Gallery: Alibaba vector icon library .

two point three   Add foreground code for "microblog login" button

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 "microblog login" button image:

<div style="line-height: 22px;margin:0 0 8px 0;color: #9b9b9b;">
        <span style="vertical-align:middle">Third party login:</span>
        <img :src="qqIcon" width="22" height="22" style="vertical-align:middle;margin-left: 2px" title="QQ" @click="handleQqLogin">
        <a href=""><img :src="weixinIcon" width="22" height="22" style="vertical-align:middle;margin-left: 2px" title="WeChat"></a>
        <img :src="weiboIcon" width="22" height="22" style="vertical-align:middle;margin-left: 2px" title="micro-blog" @click="handleWeiBoLogin">
        <a href=""><img :src="qyweixinIcon" width="22" height="22" style="vertical-align:middle;margin-left: 2px" title="Enterprise wechat"></a>
</div>

 

// Microblog login
// https://api.weibo.com/oauth2/authorize?client_id=203394&response_type=code&redirect_uri=https%3A%2F%2Fwww.lovezmy.link%2FweiBoCallback&state=439b3e51799553ab
handleWeiBoLogin() {
getWeiBoCode().then(res => {
window.location.href = res;
})
},

2.3.2 back end code (Java)

Microblog login profile information:

# Microblog login configuration
weibo.appID = 266666664(Replace with your)
weibo.appKEY = 666666666613a0b31579(Replace with your)
weibo.redirectURI = https://www.lovezmy.link/weiBoCallback (replace with yours)
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

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;

/**
* Microblog login constant configuration class
*/

@Data
@Configuration
@PropertySource("classpath:thirdparty/config.properties") // Specify the path of the configuration file. The property file must be placed under the resources folder of the root directory before it can be read out
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;

}

Conteoller (get the url of microblog login)

   /**
     * Get the url to jump to the microblog login page and directly a connect to the front desk
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation("Get to jump to the microblog login page url")
    @ApiOperation("Get to jump to the microblog login page url")
    @AnonymousAccess
    @GetMapping("/getWeiBoCode")
    public ResponseEntity<Object> getWeiBoCode() throws Exception {
        // Authorized address ,conduct Encode transcoding 
        String authorizeURL = weiBoConstants.getAuthorizeURL();

        // token url  ,Callback address to be Encode transcoding 
        String redirectUri = weiBoConstants.getRedirectURI();

        //Prevention for third party applications CSRF attack
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // Save to Redis
        redisUtils.set(WEIBOSTATE + "-" + uuid, uuid, expiration, TimeUnit.MINUTES);

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

        return ResponseEntity.ok(url);
    }

3. Obtain the authorized Access Token

The purpose of this step:

Obtain the Access Token through user authentication, login and authorization, so as to prepare for obtaining the user's uid in the next step.

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

Server side mode, yes OAuth2.0 certification It is also called Web Server Flow.

It is applicable to applications that need to be accessed from the web server, such as Web sites.

three point two   Get Authorization Code

Request address:

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

Request method:

  GET/POST

Request parameters:

 Mandatory Type and scopeexplain
client_id true string AppKey assigned when applying for application.
redirect_uri true string For the authorized callback address, the off-site application shall be consistent with the set callback address, and the on-site application shall fill in the address of canvas page.
scope false string Parameters required to apply for scope permissions. You can apply for multiple scope permissions at one time, separated by commas. Working with documents
state false string It is used to maintain the status of request and callback. During callback, the parameter will be returned in Query Parameter. The developer can use this parameter to verify the validity of the request, and can also record the position 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 following description for the value.
forcelogin false boolean Whether to force users to log in again. true: Yes, false: No. The default is false.
language false string The language of the authorization page is simplified Chinese by default, and en is English. In the English version of the test, any comments of the developer can be fed back to @ microblog API

Return Description:

1. If the user successfully logs in and authorizes, it will jump to the specified callback address and log in to redirect_ The URI address is followed by the Authorization Code and the original state value. For example:

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

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

three point three   Obtain Access Token through Authorization Code

Request address:

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

Request method:

  POST

Request parameters:

 Mandatory Type and scopeexplain
client_id true string AppKey assigned when applying for 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 code value obtained by calling authorize.
rediect_url ture string The callback address shall be consistent with the callback address in the registered application.

Return Description:

Return value fieldField typeField description
access_token string The only ticket authorized by the user is used to call the open interface of microblog. At the same time, it is also the only ticket for the third-party application to verify the login of microblog users. The third-party application should establish a unique mapping relationship with the users in its own application to identify the login status. The UID field in this return value cannot be used for login identification.
expires_in string access_ The life cycle of a token, in seconds.
remind_in string access_ The life cycle of the token (this parameter is about to be discarded. Please use expires_in for developers).
uid string The UID of the authorized user. This field is only returned for the convenience of developers to reduce one user/show interface call. Third party applications cannot use this field as the identification of user login status, only access_ The token is the only ticket authorized by the user.
{
  "access_token":"2.00kAsM_435345353349baFTDB",
"remind_in":"157679999", "expires_in":157679999, "uid":"6342222336", "isRealName":"true"
}

Interface code:

   /**
     * Obtain the token information (authorization is different for each user) - > obtain the token information. The duration of the token returned in this step is one month
     *
     * @return
     * @throws Exception
     */
    public Map<String, Object> getToken(String code) throws Exception {
        Map<String, Object> weiBoProperties = new HashMap<String, Object>();
        try {
            //  https://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=CODE
            StringBuilder url = new StringBuilder();
            url.append(weiBoConstants.getAccessToken());
            url.append("?client_id=" + weiBoConstants.getAppID());
            url.append("&client_secret=" + weiBoConstants.getAppKEY());
            url.append("&grant_type=authorization_code");
            // token url 
            String redirectUri = weiBoConstants.getRedirectURI();
            // transcoding 
            url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirectUri));
            url.append("&code=" + code);

            // get token
            String result = HttpUtil.post(url.toString(), "UTF-8");// hold token preservation
            JSONObject object = JSONObject.fromObject(result);
            //token information
            weiBoProperties = new HashMap<String, Object>();
            weiBoProperties.put("accessToken", object.getString("access_token"));
            weiBoProperties.put("remindIn", object.getString("remind_in"));
            weiBoProperties.put("expiresIn", object.getString("expires_in"));
            weiBoProperties.put("uid", object.getString("uid"));
        } catch (Exception e) {
            throw new BadRequestException("Microblog login information is abnormal, please try again!!!");
        }
        return weiBoProperties;
    }

five   OpenAPI call description_ OAuth2.0

The purpose of this step:

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

Request address:

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

Request method:

  GET

Request parameters:

 Mandatory Type and scopeexplain
access_token true string OAuth authorization method is a required parameter, which can be obtained after OAuth authorization.
uid true int64 User ID to query.

Return Description:

package com.modules.security.entity;

import lombok.Data;
import java.io.Serializable;

/**
 * Microblog login user information
 *
 * @author Liyh
 * @date 2020/12/22
 */

@Data
public class WeiBoUserInfo implements Serializable {
    private String idstr;                    // String user UID
    private String screen_name;              // User nickname
    private String name;                     // Friendly display name
    private String province;                 // User's Province ID
    private String city;                     // User's City ID
    private String location;                 // User location
    private String description;              // User personal description
    private String url;                      // User blog address
    private String profile_image_url;        // User avatar address (middle picture), 50×50 pixel
    private String profile_url;              // User's microblog unified URL address
    private String domain;                   // User's personalized domain name
    private String weihao;                   // User's Micro number
    private String gender;                   // Gender, m: Male f: Female n: unknown
    private String followers_count;          // Number of fans
    private String friends_count;            // Number of concerns
    private String statuses_count;           // Number of microblogs
    private String favourites_count;         // Number of collections
    private String created_at;               // User creation (Registration) time
    private String following;                // Not supported yet
    private String allow_all_act_msg;        // Will everyone be allowed to send me private messages, true: Yes, false: no
    private String geo_enabled;              // Whether to allow identifying the geographical location of the user, true: Yes, false: no
    private String verified;                 // Whether it is a microblog authenticated user, i.e. plus V Users, true: Yes, false: no
    private String verified_type;            // Whether it is a microblog authenticated user, i.e. plus V Users, true: Yes, false: no
    private String remark;                   // This field is only returned when querying user relationship
    private String allow_all_comment;        // Allow everyone to comment on my microblog, true: Yes, false: no
    private String avatar_large;             // User avatar address (large picture), 180×180 pixel
    private String avatar_hd;                // User avatar address (hd), HD avatar original
    private String verified_reason;          // Certification reason
    private String follow_me;                // Whether the user pays attention to the currently logged in user, true: Yes, false: no
    private String online_status;            // User's online status, 0: not online, 1: Online
    private String bi_followers_count;       // Number of users
    private String lang;                     // The user's current language version, zh-cn: Simplified Chinese, zh-tw: Traditional Chinese, en: English
}

Interface code:

   /**
     * accessToken,uid Get user information
     */
    public String getUserJson(Map<String, Object> weiBoProperties) throws Exception {
        String result = null;
        try {
            // take out token
            String accessToken = (String) weiBoProperties.get("accessToken");
            String uid = (String) weiBoProperties.get("uid");
            if (StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(uid)) {
                throw new BadRequestException("Microblog login information is abnormal, please try again!!!");
            }
            // Splicing url
            StringBuilder url = new StringBuilder();
            url.append(weiBoConstants.getUserJson());
            url.append("?access_token=" + accessToken);
            url.append("&uid=" + uid);

            // Obtain data related to microblog user information
            result = HttpClientUtils.get(url.toString(), "UTF-8");
        } catch (Exception e) {
            throw new BadRequestException("Microblog login information is abnormal, please try again!!!");
        }
        return result;
    }

 

6 personal websites( YOUYOUSHOP ), QQ and microblog have been implemented, and the required partners can test  

six point one   The definition of error code in OAuth2.0 error response is shown in the following table:

Error code (error)Error_codeError_description
redirect_uri_mismatch 21322 Redirect address mismatch
invalid_request 21323 Illegal request
invalid_client 21324 client_id or client_ Invalid secret parameter
invalid_grant 21325 The provided Access Grant is invalid, expired, or revoked
unauthorized_client 21326 The client does not have permission
expired_token 21327 token expiration
unsupported_grant_type 21328 Unsupported GrantType
unsupported_response_type 21329 Unsupported ResponseType
access_denied 21330 The user or authorized server refused to grant data access
temporarily_unavailable 21331 The service is temporarily inaccessible
appkey permission denied 21337 Insufficient application permissions

6.2 each person's project needs are different, and different problems may occur. You can refer to the article or leave a message about your problem. I will help you solve it. Let's cheer together

 

Tags: Java Spring Boot Vue

Posted on Fri, 03 Dec 2021 09:55:24 -0500 by PhantomCube