This article is included in my personal blog: www.chengxy-nds.top, Technical Resource Sharing.

Last article “OAuth2.0 four kinds of authorization” at the end of the article said, the follow-up to a wave of OAuth2.0 combat, delayed a few days today finally make up.

Recently, WHEN I was working on my own open source project (Fire), the front and back end separation framework of Springboot + Vue was just built. At the beginning of the login function, I felt that the password login of ordinary account was too simple and meaningless, so I kept thinking about it in order to force it to be higher. We decided to add GitHub authorization and face recognition to the list.

Insert a picture description here

GitHub authorization login just used OAuth2.0 in the most complex authorization code mode, just take my case to share the OAuth2.0 authorization process, the subsequent project functions will continue to update.

I. Authorization process

Before specifically doing GitHub authorized login, let’s briefly review the authorization process of OAuth2.0 authorization code mode. If fire website allows to log in with GitHub account, the process is roughly as shown in the following figure.

Insert a picture description here

Users want to log in to the Fire site using their GitHub account:

  • fireThe site first directs users toGitHubAn authorization dialog box is displayed.
  • After the user agrees,GitHubDepending on theredirect_uriRedirects back to thefireSite, and return an authorization code code.
  • fireWeb sites use authorization codes and client keysclient_secret, request a token from GitHubtoken, check to pass the return token.
  • The lastfireWeb site toGitHubRequest data each time GitHub’sAPIWe all need to carry a token.

2. Identity registration

With the authorization logic sorted out, we still have some work to do.

To obtain OAuth authorization for a site, you must go to its website to register your identity and get the application’s identity codes ClientID and ClientSecret.

There are several mandatory registration portal https://github.com/settings/applications/1334665,.

  • Application name: Our app name;
  • Homepage URL: App home page link;
  • Authorization callback URLThis is:githubCall back the address of our project to get the authorization code and token.

Once you submit it, you’ll see the client ClientID and the client key ClientSecret, and that’s where we’re done.

Insert a picture description here

Iii. Authorized development

1. Obtain the authorization code

In order to better see the effect, I dealt with the authorization code rather rough, directly assembled the authorization link in JS, but the actual work development must take into account the security problem.

https://github.com/login/oauth/authorize?
client_id=ad41c05c211421c659db&
redirect_uri=http:/ / 47.93.6.5:8080 / the authorize/redirect
Copy the code

The logic of the front-end vue is very simple, just a window.location.href redirect.

<script>
export default {
  methods: {
    loginByGithub: function () {
      window.location.href = 'https://github.com/login/oauth/authorize?client_id=ad41c05c211421c659db&redirect_uri=http://47.93.6.5:8080/authorize/re direct'
 }  } } </script> Copy the code

After the request, it will prompt us to authorize. After the authorization is approved, it will redirect to authorize/redirect, and carry the authorization code. If you have agreed before, you will skip this step and call back directly.

Insert a picture description here

2. Get the token

The authorization is then followed by a callback to the Fire site interface, where the authorization code is obtained and the request link for the access_token is assembled using the client key client_secret.

https://github.com/login/oauth/access_token? 
    client_id=${clientID}& 
    client_secret=${clientSecret}& 
    code=${requestToken}
Copy the code

The access_token is returned as a request response, and the result is a string character that we need to intercept.

access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c&scope=&token_type=bearer
Copy the code

Once you have a token and start retrieving user information, you need an access_token in your API.

https://api.github.com/user?access_token=4dc43c2f43b773c327f97acf5dd66b147db9259c
Copy the code

The returned user information is in JSON data format. If you want to pass the data to the front end, you can redirect the data to the front end page through the URL and pass the data as parameters.

{
    "login": "chengxy-nds".    "id": 12745094.    "node_id": "".    "avatar_url": "https://avatars3.githubusercontent.com/u/12745094?v=4". "gravatar_id": "". "url": "https://api.github.com/users/chengxy-nds". "html_url": "https://github.com/chengxy-nds". "followers_url": "https://api.github.com/users/chengxy-nds/followers". "following_url": "https://api.github.com/users/chengxy-nds/following{/other_user}". "gists_url": "https://api.github.com/users/chengxy-nds/gists{/gist_id}". "starred_url": "https://api.github.com/users/chengxy-nds/starred{/owner}{/repo}". "subscriptions_url": "https://api.github.com/users/chengxy-nds/subscriptions". "organizations_url": "https://api.github.com/users/chengxy-nds/orgs". "repos_url": "https://api.github.com/users/chengxy-nds/repos". "events_url": "https://api.github.com/users/chengxy-nds/events{/privacy}". "received_events_url": "https://api.github.com/users/chengxy-nds/received_events". "type": "". "site_admin": false. "name": "Programmer internal matters.". "company": null. "blog": "". "location": null. "email": "". "hireable": null. "bio": null. "twitter_username": null. "public_repos": 7. "public_gists": 0. "followers": 14. "following": 0. "created_at": "2015-06-04T09:22:44Z". "updated_at": "2020-07-13T06:08:57Z" } Copy the code

Below is the GitHub callback to our fire website back-end processing process part of the code, written relatively rough, continue to optimize the subsequent!

/ * *     * @param code
     * @author xiaofu
* @description Authorization callback * @date 2020/7/10 15:42 * /  @RequestMapping("/authorize/redirect")  public ModelAndView authorize(@NotEmpty String code) {   log.info("License Code: {}", code);   / * ** Go back to the front page* /  String redirectHome = "http://47.93.6.5/home";   try {  / * ** 1, assemble get accessToken URL* /  String accessTokenUrl = gitHubProperties.getAccesstokenUrl()  .replace("clientId", gitHubProperties.getClientId())  .replace("clientSecret", gitHubProperties.getClientSecret())  .replace("authorize_code", code);   / * ** Returns the token directly in the result* /  String result = OkHttpClientUtil.sendByGetUrl(accessTokenUrl);  log.info(Request token result: {}, result);   String accessToken = null;  Pattern p = Pattern.compile("=(\\w+)&");  Matcher m = p.matcher(result);  while (m.find()) {  accessToken = m.group(1);  log.info("Token: {}", m.group(1));  break;  }   / * ** After the token is successfully obtained, the user information is requested* /  String userInfoUrl = gitHubProperties.getUserUrl().replace("accessToken", accessToken);   String userResult = OkHttpClientUtil.sendByGetUrl(userInfoUrl);   log.info("User information: {}", userResult);   UserInfo userInfo = JSON.parseObject(userResult, UserInfo.class);   redirectHome += "? name=" + userInfo.getName();   } catch (Exception e) {  log.error("Authorization callback exception ={}", e);  }  return new ModelAndView(new RedirectView(redirectHome));  } Copy the code

Finally, let’s take a look at the overall authorization process in the GIF. Due to the slow access speed of GitHub, occasionally the request times out.

Insert a picture description here

Online preview address: http://47.93.6.5/login, welcome to experience ~

Project making address: https://github.com/chengxy-nds/fire.git

conclusion

From the whole GitHub authorization login process, OAuth2.0 authorization code mode is relatively simple, understand a GitHub login, like wechat, weibo and other three login will also be completely similar things, interested students can try.

Original is not easy, burning hair output content, if there is a lost harvest, a praise to encourage it!

I sorted out hundreds of technical e-books and gave them to my friends. Pay attention to the public number reply [666] to get yourself. I set up a technology exchange group with some friends to discuss technology and share technical information, aiming to learn and progress together. If you are interested, just scan code and join us!