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

1. Preparatory work_OAuth2 (official website address: development process )

1.1 API Terms of Use

  1. OSCHINA users are the owners of resources and need to respect and protect the rights and interests of users.

  2. The name of OSCHINA cannot be used in the application.

  3. Without the permission of the user, it is not allowed to crawl or store the user's resources.

  4. Abuse of the API is prohibited. Excessive request frequency will cause the request to be terminated.

1.2 Basic flow of OAuth2 authentication

1. Initiate an authorization request to the Gitee server through the applied application ID – Client ID, callback address, etc.

2. The Gitee authentication server passes back the user authorization code code through the callback address {redirect_uri} [pass to the callback address]

3. Through the user authorization code code and application ID and other information, go to the Gitee server to obtain the user's access token (Access Token)

4. After obtaining the Access Token, go to the Gitee server to obtain the user's ID, name, email and other information according to the token

2. Place the "Gitee Login" button

The role of this step :

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

2.1 Download the "Gitee Login" button picture, and place the button in the appropriate position on the page

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

2.2 Add the "Gitee 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 "Gitee Login" button image:

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

1. Gitee login configuration file information:

# gitee登录配置
gitee.appID = 679f486666666666666660b0022d43b2(替换自己的)
gitee.appKEY = c37e5666666666666666666666666666666618be(替换自己的)
gitee.redirectURI = https://www.youyoushop.work/giteeCallback(替换自己的)
gitee.authorizeURL = https://gitee.com/oauth/authorize
gitee.accessToken = https://gitee.com/oauth/token
gitee.userInfo = https://gitee.com/api/v5/user

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;

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

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

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

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

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

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

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

}

3. Conteoller (get the url of Gitee login)

/**
     * 获得跳转到Gitee登录页的url,前台直接a连接访问
     *
     * @return
     */
    @GetMapping("/getGiteeCode")
    public Result getGiteeCode() {
        // 授权地址 ,进行Encode转码
        String authorizeURL = giteeConstants.getAuthorizeURL();

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

        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

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

        return Result.success("操作成功", url);
    }

3. Get AccessToken

3.1 Get Authorization Code

Note: If you need to skip the authorization page if you have been authorized before, you need to add the scope parameter to the URL in the first step above, and the value of scope needs to be consistent with the user's last authorization check.

Request address :

https://gitee.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&scope=user_info

Request method :

  GET

Request parameters :

parameter Is it necessary meaning
response_type must Authorization type, this value is fixed as "code".
client_id must The appid assigned to the application after successfully logging in to Gitee.
redirect_uri must The callback address after successful authorization must be the address under the main domain name filled in when registering the appid. It is recommended to set it as the homepage of the website or the user center of the website. Note that the url needs to be URLEncoded.
state optional The status value of the client. It is used by third-party applications to prevent CSRF attacks. After successful authorization, it will be returned as it is when calling back. Be sure to check the binding of the user and the state parameter state strictly according to the process.
scope must The list of available authorizations shown to the user when requesting user authorization.
Request to authorize the interface user_info.
It is recommended to control the number of authorization items and only pass in the necessary interface names, because the more authorization items, the more likely the user will refuse to perform any authorization.

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 original state value after the redirect_uri address. like:

https://www.youyoushop.work/giteeCallback?code=1E83738E1231233B1224D9B3C&state=cca3c152c52722123123d2963fe

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

3.2 Obtain Access Token through Authorization Code

The application server or Webview uses the access_token API to send a post request to the code cloud authentication server to pass in the user authorization code and callback address (  POST request  )

Note: During the request process, it is recommended to put client_secret in the Body to pass the value to ensure data security.

Request address :

https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}

Request method :

  POST

Request parameters :

parameter Is it necessary meaning
grant_type must Authorization type, in this step, the value is "authorization_code".
client_id must The appid assigned to the website after applying for Gitee to log in successfully.
client_secret must The appkey assigned to the website after successfully logging in with Gitee.
code must The authorization code returned in the previous step.
redirect_uri must Be consistent with the redirect_uri passed in in the previous step.

Return instructions :

  If the return is successful, the Access Token can be obtained in the return packet. For example (when fmt is not specified):

access_token=FE04************CCE2&expires_in=7776000&refresh_token=88E4****************BE14
Parameter Description describe
access_token Authorization token, Access_Token.
expires_in The validity period of the access token, in seconds.
refresh_token Parameters that need to be provided when obtaining a new Access_Token in the authorization auto-renewal step.

Note: refresh_token is only valid once

Error code description :

 If access_token returns 403, it may be because User-Agent is not set.

 For details, see: What happens when the server responds with a status of 403 when obtaining a Token?

3.4 (Optional) Automatically renew permissions and refresh Access Token

  When the access_token expires (valid for one day), you can re-acquire the access_token through the following refresh_token method

Request address :

https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}

Request method :

  POST

Request parameters :

parameter Is it necessary meaning
grant_type must Authorization type, in this step, this value is "refresh_token".
refresh_token must First time: use the latest refresh_token obtained in Step2 .

Follow-up: use the latest refresh_token returned after refresh

Error code description :

 If access_token returns 403, it may be because User-Agent is not set.

 For details, see: What happens when the server responds with a status of 403 when obtaining a Token?

4. Get user information

Request address:

https://gitee.com/api/v5/user?access_token=xxx&

Request method:

  GET

Request parameters:

parameter Is it necessary meaning
access_token must The access token obtained in Step1.

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

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

5.2 SpringBoot+Vue implements third-party Gitee login (1)

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

6. Source code purchase

6.1 Concise version ( Taobao source code )

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

6.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/131088181