Recently, WHEN I was perfecting my blog system, I suddenly thought of changing from temporarily filling in name + email to Posting comments to logging in with GitHub authorization.

Cut to the chase and get right to the point

Tips: This article is for personal use only. If you need to learn more details about how to use OAuth, please visit the official documentation.

Create a request Apps

First, you need a GitHub account and then go to GitHub developers. After filling in according to the requirements, Client_ID and Client Secret will be generated automatically, which will be used in the following steps.

Access code

//method
async githubLogin() {
	windows.location.href = 
    "https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri"
}
Copy the code
<a href="https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri">Lot of landing</a>
Copy the code

The route parameter redirect_URI is optional. If omitted, GitHub will redirect to the callback path you configured in OAuth Apps. If provided, the redirect_URI you specified must be a subpath of the callback path you configured in OAuth Apps. As follows:

CALLBACK: http://xx.com/github

GOOD: http://xx.com/github
GOOD: http://xx.com/github/path/path
BAD: http://xx.com/git
BAD: http://xxxxx.com/path
Copy the code

If the user accepts your request, it will jump to redirect_URI, and we can accept the code parameter in the route for the next step.

your_redirect_uri? code=xxxCopy the code

Get access_token

We need client_id, client_secret, and code to get the access_token.

/*
/githubAccessToken:https://github.com/login/oauth/access_token
*/
this.$axios
	.get('/githubAccessToken', {params: {
		client_id: your_client_id,
		client_secret: your_client_secret,
		code: your_code
		}
	})
Copy the code

By default, you get the following response:

access_token=xxxxx&token_type=bearer
Copy the code

If you want to receive the response in a more convenient format, you can customize Accept in headers:

Accept: "application/json"= > {"access_token":xxxxx,"token_type":bearer}
Copy the code

Obtaining User information

After obtaining the access_token, we can request some information about the user:

/*
/githubUserInfo:https://api.github.com/user
*/
this.$axios
	.get('/githubUserInfo', {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded".Accept: "application/json".Authorization: `token ${access_token}` / / required}})Copy the code

Then you can get the user information.