Когда и почему Passport.js необходим для реализации GitHub OAuth 2.0?
Я интегрировал GitHub OAuth Login без Passport.js в свое приложение Node.js, используя Express и Axios, и он работает отлично. Итак, когда и зачем нужен Passport.js?
// Import the express library
const express = require('express')
// Import the axios library, to make HTTP requests
const axios = require('axios')
// This is the client ID and client secret that you obtained
// while registering the application
const clientID = '' //add your own ID
const clientSecret = '' //add your own secret
// Create a new express application and use
// the express static middleware, to serve all files
// inside the public directory
const app = express()
app.use(express.static(__dirname + '/public'))
app.get('/oauth/redirect', (req, res) => {
// The req.query object has the query params that
// were sent to this route. We want the `code` param
const requestToken = req.query.code
axios({
// make a POST request
method: 'post',
// to the Github authentication API, with the client ID, client secret
// and request token
url: `https://github.com/login/oauth/access_token?client_id=${clientID}&client_secret=${clientSecret}&code=${requestToken}`,
// Set the content type header, so that we get the response in JSON
headers: {
accept: 'application/json'
}
}).then((response) => {
// Once we get the response, extract the access token from
// the response body
const accessToken = response.data.access_token
// redirect the user to the welcome page, along with the access token
res.redirect(`/welcome.html?access_token=${accessToken}`)
})
})
// Start the server on port 8080
app.listen(8080, function () {
console.log('App listening at port: 8080');
});