This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

Have you ever thought about implementing a third party app login when you’re doing your own projects? Something like this:

In this article, we’ll talk about how to implement third-party application logins.

What is a OAuth2.0

OAuth is a protocol that provides a secure, open and simple standard for the authorization of user resources. OAuth’s authorization does not allow a third party to access the user’s account information (such as password), so OAuth is relatively secure. OAuth2.0 is a continuation of OAuth, but focuses more on simplicity for client developers.

Applying for website access

Common third-party applications support third-party login, such as QQ, wechat, Weibo, GitHub, Gitee, etc. To apply for third-party login, you need to go to the corresponding platform, such as QQ, and search for QQ open platform:

Enter the application management and create the application:

However, the access to QQ, wechat, Weibo and other websites requires identity authentication, which is complicated, so we use Gitee as a third-party application for access.

First, open Gitee and select Settings:

Select third-party applications in Settings:

Click Create App and fill in the information:

The application name can be filled in at will, but the following two addresses are useful. For the application home page, it needs to fill in the current application home page, while the application callback interface fills in the page to jump to when the login is successful.

Create the SpringBoot application

Once the application is complete, you can create the SpringBoot application and create a new index. HTML page:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
  <body>
    <form>User name:<input type="text"/><br/>Password:<input type="password"/><br/>
      <a href="">Gitee login</a>
      <input type="submit" value="Login"/><br/>
    </form>
  </body>
</html>
Copy the code

The effect is as follows:

The page is ugly, but it doesn’t matter, just implement the function.

Now our requirement is that clicking on the Gitee login link will redirect us to a third party login page like this:

So how do you do that?

Back in Gitee, after you’ve created your application, drag the page to the bottom and you’ll see the mock request button:

Clicking this button will give you a simulated login:

The address in the address bar is the page we need to jump to. Copy the address down:

https://gitee.com/oauth/authorize?client_id=52908197466cd3008db76a6018de66c8d222656056fa78b26dd58d1f4fa0a606&redirect_uri=http %3A%2F%2Flocalhost%3A8080%2Fsuccess&response_type=code
Copy the code

There are three parameters in total, which are:

  1. client_id
  2. redirect_uri
  3. response_type

Client_id is provided to us after the application is created:

Redirect_uri is the page to be redirected to when the consent button is clicked. When the login succeeds, the page to be redirected to is the successful page, and finally response_type, which indicates that the response type is an authorization code.

When the user clicks the authorization button, the Gitee server will pass an authorization code to the page pointed to by redirect_URI. At this time, the Gitee server can receive the authorization code and exchange for the AccessToken. To obtain some information about the current user in Gitee.

After clicking the Grant button:

After obtaining the authorization code, the address can be exchanged for the AccessToken:

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

PostMan = PostMan; PostMan = PostMan; PostMan = PostMan;

The corresponding results are obtained:

{
  "access_token": "cd2c33c3fe548a23188159f87da70110"."token_type": "bearer"."expires_in": 86400."refresh_token": "c95a38ab2357638ffc4dc6f09c623f2333e0930a37dec8e2f191a40d7afd3514"."scope": "user_info"."created_at": 1627974370
}
Copy the code

Once you have access to AccessToken, you can access any information that the user has authorized in Gitee.

The whole authentication process is shown in the figure below:

Implementing the login process

After we are familiar with the integration process, let’s use the code to implement it. First, modify the page:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
  <body>
    <form>User name:<input type="text"/><br/>Password:<input type="password"/><br/>
      <a href="https://gitee.com/oauth/authorize?client_id=52908197466cd3008db76a6018de66c8d222656056fa78b26dd58d1f4fa0a606&redirect_u ri=http%3A%2F%2Flocalhost%3A8080%2Fsuccess&response_type=code">Gitee login</a>
      <input type="submit" value="Login"/><br/>
    </form>
  </body>
</html>
Copy the code

Hyperlink address after modification can now successful jump to Gitee authorization page, because the address of the authorized after a successful jump for http://localhost:8080/success, so I need to handle the request, to create a controller:

@Controller
public class LoginController {

    @GetMapping("/success")
    public String login(@RequestParam("code") String code){
        System.out.println(code);
        return "success";
    }
    
    @GetMapping("/")
    public String index(a){
        return "index"; }}Copy the code

When the authorization is successful, we make it jump to the success. HTML page and receive the authorization code from Gitee, so create success. HTML:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
  <body>
    <h1>Login successful!</h1>
  </body>
</html>
Copy the code

Start the project and test it:

Click “Agree” and the login succeeds. The console also outputs the authorization code:

e907fd92d8392ebcd72dff321da45115ff0fba2dec0e6918b233ec7d03b76e5d
Copy the code

In fact, the login process is not over yet, because if you use a third-party application to log in, the platform will use some information of the third-party application, such as account and profile picture, as the login name and profile picture of the current platform, so we still need to obtain some information of users in Gitee.

Refer to the Gitee API documentation here:

For example, to obtain information about authorized users:

It needs to pass an access_token as an argument, so all we need to do is use the authorization code to get the access_key:

@Controller
public class LoginController {

    @GetMapping("/success")
    public String login(@RequestParam("code") String code, Map<String,String> map) {
        / / get the accesskey
        String accessKey = getAccessKey(code);
        System.out.println(accessKey);
        // Obtain user information using the accessKey
        String userInfo = getUserInfo(accessKey);
        // Fetch the user name
        String name = (String) JSONObject.parseObject(userInfo).get("name");
        // Take out the head
        String avatar_url = (String) JSONObject.parseObject(userInfo).get("avatar_url");
        // Put in the request domain
        map.put("name",name);
        map.put("avatar_url",avatar_url);
        return "success";
    }

    /** * Obtain user information */
    private String getUserInfo(String accessKey) {
        String json = "";
        OkHttpClient client = new OkHttpClient();
        // User information can be obtained from this address
        String url = "https://gitee.com/api/v5/user?access_token=" + accessKey;
        Request request = new Request.Builder()
                .get()
                .url(url).build();
        try {
            Response response = client.newCall(request).execute();
            json = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    /** * Obtain AccessKey */
    private String getAccessKey(String code) {
        OkHttpClient client = new OkHttpClient();
        // The access_token can be obtained from this address
        String url = "https://gitee.com/oauth/token";
        // Encapsulate the request parameters
        RequestBody requestBody = new FormBody.Builder()
                .add("grant_type"."authorization_code")
                .add("code", code)
                .add("client_id"."52908197466cd3008db76a6018de66c8d222656056fa78b26dd58d1f4fa0a606")
                .add("redirect_uri"."http://localhost:8080/success")
                .add("client_secret"."7e84401a9752e88d22d5450c1687ca6a19bc34f45fe3452cefd33312d8153978")
                .build();

        Request request = new Request.Builder()
                .post(requestBody)
                .url(url).build();
        String accessKey = "";
        try {
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            // Obtain the access_token attribute in the JSON string
            accessKey = (String) JSONObject.parseObject(json).get("access_token");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return accessKey;
    }

    @GetMapping("/")
    public String index(a) {
        return "index"; }}Copy the code

The success. HTML page needs to display user information:

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
  </head>
  <body>
    <h1>Login successful!</h1>
    <h1>User name:<span th:text="${#request.getAttribute('name')}"></span></h1>
    <img th:src="${#request.getAttribute('avatar_url')}">
  </body>
</html>
Copy the code

The effect is as follows:

In fact, the login process is not so simple, when a user cancel the authorization will not be able to make the login, program has not yet been combined with this kind of judgment, for never registered users, this login is equivalent to a register, so you also need to Gitee in certain user information to log in as a registered information, when the already registered user login using a third party, You want it to log in.