OAuth (License)
Three-party login is mainly based on OAuth 2.0. OAuth protocol provides a safe, open and simple standard for user resource authorization. Different from previous authorization methods, OAUTH authorization does not allow the third party to touch the user’s account information (such as user name and password), that is, the third party does not need to use the user’s user name and password to apply for the authorization of the user resources, so OAUTH is safe.
The practical application
This section describes how to log in to Github as a third party when vUE is used in the front-end and KOA is used in the back-end
Making configuration
First go to Github -> Settings -> Developer Settings -> Github Apps -> OAuth Apps -> Click New OAuth App, enter the following interface
http://localhost:8080/github/callback
Vue under the code
login(){
this.$axios({
method: 'get'.url: '/test/github/login'.params: {
path: 'http://localhost:8080'+this.$route.fullPath
}
}).then((res) = >{
console.log(res)
window.location.href=res.data; })}Copy the code
The front end requests the back end with the current address (easy to jump back to later). The background returns the authentication address and parameters, using window.location.href to jump.
Implementation under KOA
const config={
client_id:'xxxx'.// Github generated ID and password
client_secret:'xxxxxxx'
};
let redirectPath='http://localhost:8080/'
router.get('/github/login'.async (ctx)=>{
if(ctx.query.path) redirectPath=ctx.query.path
var dataStr=(new Date()).valueOf();
// Redirect to the authentication interface and set parameters
var path="https://github.com/login/oauth/authorize";
path+='? client_id='+config.client_id;
// Return the address and parameters to the front end
ctx.body=path;
});
// Github callback after authentication
router.get('/github/callback'.async (ctx)=>{
console.log('callback... ')
const code=ctx.query.code; // Return the authorization code
const params={
client_id:config.client_id,
client_secret: config.client_secret,
code:code
}
// With this authorization code, request a token from GitHub
let res=await axios.post('https://github.com/login/oauth/access_token', params)
const access_token=querystring.parse(res.data).access_token
// Get user information by token
res=await axios.get('https://api.github.com/user?access_token=' + access_token)
// console.log('userAccess:', res.data)
// ctx.body = res.data
ctx.cookies.set('user',res.data.login) // User name
ctx.cookies.set('icon',res.data.avatar_url) // User image
ctx.redirect(redirectPath) // Redirect to the request page
})
Copy the code
The back-end end obtains user information through a series of requests and returns it to the front-end interface in the form of cookies (or parameters). At this point, the front-end end completes a third-party login on Github.