Используя паспортную стратегию Twitter js, я аутентифицировал маршрут своего узла с помощью модуля passport.authenticate и смог войти в систему, чтобы получить данные пользователя из запроса.
Проблема начинается при получении / запросе после аутентификации в функции обработчика. Некоторое время я не мог сделать запрос к конечной точке Twitter без сообщения о состоянии 400. Я скачал почтальон и смог увидеть, что не так с моим извлечением / запросом, так как, несмотря на то, что мой маршрут был аутентифицирован, извлечение / запрос с другой стороны не был авторизован с такими деталями, как oauth_consumer_key, oauth-токен, oauth-метод подписи и все остальное отображается в ключе авторизации (в основном отсутствовал ключ авторизации со значениями, показанными ниже, скопированными из почтальона).
Итак, как мне получить эти динамические c учетные данные для авторизации без необходимости вручную вводить их в строку запроса / получения кода.
const express = require('express')
const router = express.Router()
const passport = require('passport')
const authController = require('./auth.controller')
const fetch = require('node-fetch')
const request = require('request');
// Setting up the passport middleware for each of the OAuth providers
const twitterAuth = passport.authenticate('twitter')
const googleAuth = passport.authenticate('google', { scope: ['profile'] })
const facebookAuth = passport.authenticate('facebook')
const githubAuth = passport.authenticate('github')
const handler = (req, res, next)=>{
const options = {
'method': 'GET',
'url': 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=username&count=1',
'headers': {
'Content-Type': '',
'Authorization': 'OAuth oauth_consumer_key="XXXXXXXXXXX",oauth_token="XXXX-XXXXXXXXXXXXXXXXXXX",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1582893903",oauth_nonce="XXXXXXXXX",oauth_version="1.0",oauth_signature="XXXXXXXXXXXXXXXXXXXX"'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
next()
}
// Routes that are triggered by the callbacks from each OAuth provider once
// the user has authenticated successfully
router.get('/twitter/callback', passport.authenticate("twitter", {failureRedirect: '/twitt'}), handler, authController.twitter)
router.get('/google/callback', googleAuth, authController.google)
router.get('/facebook/callback', facebookAuth, authController.facebook),
router.get('/github/callback', githubAuth, authController.github)
// This custom middleware allows us to attach the socket id to the session
// With that socket id we can send back the right user info to the right
// socket
router.use((req, res, next) => {
req.session.socketId = req.query.socketId
next()
})
// Routes that are triggered on the client
router.get('/twitter', twitterAuth)
router.get('/google', googleAuth)
router.get('/facebook', facebookAuth)
router.get('/github', githubAuth)
router.get('/twitt', (req, res)=>{
res.send('hi')
})
module.exports = router
Есть ли способ использовать паспорт? js заполнить ключ авторизации в моем запросе вызова. Таким образом, в основном у меня заполнен токен oauth, заполнен метод подписи и т. Д., Или мне придется использовать другой внешний модуль наряду с паспортом js, чтобы заполнить свои учетные данные для авторизации модулей запроса.
Пожалуйста, дайте мне знать если есть более простой способ. Любая помощь будет принята с благодарностью.
Вот и все остальное в моей конфигурации, config. js:
const providers = ['twitter', 'google', 'facebook', 'github']
const callbacks = providers.map(provider => {
return process.env.NODE_ENV === 'production'
? `https://react-auth-twitter.herokuapp.com/${provider}/callback`
: `https://localhost:8080/${provider}/callback`
})
const [twitterURL, googleURL, facebookURL, githubURL] = callbacks
exports.CLIENT_ORIGIN = process.env.NODE_ENV === 'production'
? 'https://react-auth-twitter.netlify.com'
: ['https://127.0.0.1:3000', 'https://localhost:3000']
exports.TWITTER_CONFIG = {
accessToken: 'https://api.twitter.com/oauth/authorize',
requestToken: 'https://api.twitter.com/oauth/request_token',
consumerKey: process.env.TWITTER_CONSUMER_KEY,
consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
callbackURL: twitterURL
}
//below code is not important
exports.GOOGLE_CONFIG = {
clientID: process.env.GOOGLE_KEY,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: googleURL
}
exports.FACEBOOK_CONFIG = {
clientID: process.env.FACEBOOK_KEY,
clientSecret: process.env.FACEBOOK_SECRET,
profileFields: ['id', 'emails', 'name', 'picture.width(250)'],
callbackURL: facebookURL
}
exports.GITHUB_CONFIG = {
clientID: process.env.GITHUB_KEY,
clientSecret: process.env.GITHUB_SECRET,
callbackURL: githubURL
}
passport.init. js:
const passport = require('passport')
const { Strategy: TwitterStrategy } = require('passport-twitter')
const { OAuth2Strategy: GoogleStrategy } = require('passport-google-oauth')
const { Strategy: FacebookStrategy } = require('passport-facebook')
const { Strategy: GithubStrategy} = require('passport-github')
const {
TWITTER_CONFIG, GOOGLE_CONFIG, FACEBOOK_CONFIG, GITHUB_CONFIG
} = require('../config')
module.exports = () => {
// Allowing passport to serialize and deserialize users into sessions
passport.serializeUser((user, cb) => cb(null, user))
passport.deserializeUser((obj, cb) => cb(null, obj))
// The callback that is invoked when an OAuth provider sends back user
// information. Normally, you would save the user to the database
// in this callback and it would be customized for each provider
const callback = (_accessToken, _refreshToken, profile, cb) => cb(null, profile)
// Adding each OAuth provider's strategy to passport
passport.use(new TwitterStrategy(TWITTER_CONFIG, callback))
//passport.use(new GoogleStrategy(GOOGLE_CONFIG, callback))
passport.use(new FacebookStrategy(FACEBOOK_CONFIG, callback))
//passport.use(new GithubStrategy(GITHUB_CONFIG, callback))
}
TLDR; Я хочу в основном получить все данные авторизации / аутентификации в одном запросе, чтобы передать их моему маршруту и моим учетным данным получения / запроса. Не уверен, что это можно сделать только по паспорту js.