Example of third party authorization method for vue to implement GitHub
- 2021-12-04 09:30:07
- OfStack
Recently, while improving my blog system, I suddenly thought of changing from the original temporary name + email to use GitHub authorization to log in to comment.
Don't talk too much nonsense, go straight to the topic
Tips: This article only meets personal needs. If you need to learn more detailed usage methods, you can visit the official documents of OAuth.
Create OAuth Apps
First, you need an GitHub account and then go to GitHub developers. After filling it out as required, Client_ID and Client Secret will be automatically generated, which will be used in later steps.
Get code
//method
async githubLogin() {
windows.location.href =
"https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri"
}
<a href="https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri">GitHub Landing </a>
redirect_uri is optional in the routing parameters. If omitted, GitHub will be redirected to the callback path you configured in OAuth apps. If provided, the redirect_uri you fill in 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
If the user accepts your request, it will jump to redirect_uri, and we can accept the parameter code in the route for the next step.
your_redirect_uri?code=xxx
Get access_token
We need client_id, client_secret, and code to get 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
}
})
By default, you get the following response:
access_token=xxxxx&token_type=bearer
If you want to receive responses in a more convenient format, you can customize Accept in headers:
Accept: "application/json"
=> {"access_token":xxxxx,"token_type":bearer}
Get user information
After getting access_token, we can request part of the user's information:
/*
/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
}
})
Then you can get the user information.