0

我已经使用 Express 和 Axios 在我的 Node.js 应用程序中集成了没有 Passport.js 的 GitHub OAuth Login,它运行良好。那么何时以及为什么需要 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');
});
4

0 回答 0