0

我正在我的应用程序上设置 Twitter oauth,方法是在前端create-react-app使用辅助函数 (via ) 来启动后端的 oauth 进程。我目前正在开发中,所以我将我的快速服务器托管在端口上,并将我的前端托管在端口上,前端有一个代理到端口我已经通过npm 包设置了 CORS 权限。axiospassport300130003001.cors

无论我尝试哪组配置,我都无法完成 Twitter OAuth 流程。我尝试过切换端口,保持相同的端口;我试过用express-http-proxy.

我在我的回调函数和我的初始 api 调用中都使用http://127.0.0.1了而不是,尝试了端口和.localhost30003001

我现在不确定自己哪里出错了,或者我是否需要放弃passport-twitter其他解决方案。

在每种情况下,我都会收到以下错误:

Failed to load https://api.twitter.com/oauth/authenticate?
oauth_token=alphanumericcoderedactedherebyme: No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:3000' is 
therefore not allowed access.

根据我尝试的配置,我将 origin 作为nullorhttp://localhost:3001http://127.0.0.1

请注意,由于其他原因(例如连接到Yelp Fusion API. 此外,我正在使用中间件来记录我的会话数据,我可以看到我成功地从 Twitter获取oauth_token和获取。oauth_token_secret调用在 oauth 过程的下一个阶段失败:

[0] *************SESSION MIDDLEWARE***************
[0] Session {
[0]   cookie:
[0]    { path: '/',
[0]      _expires: 2018-01-06T20:20:31.913Z,
[0]      originalMaxAge: 2678400000,
[0]      httpOnly: true },
[0]   'oauth:twitter':
[0]    { oauth_token: 'alphanumericcoderedactedherebyme',
[0]      oauth_token_secret: 'alphanumericcoderedactedherebyme' } }
[0]
[0] Logged In:
[0] __________ false
[0] **********************************************

这是我的代码的相关部分 -

后端代码

服务器.JS

// Dependencies

const express = require("express");
const cors = require("cors");
const passport = require('passport');

// Initialize Express Server
const app = express();

// Specify the port.
var port = process.env.PORT || 3001;
app.set('port', port);

app.use(passport.initialize());
app.use(passport.session());

//enable CORS
app.use(cors());

//set up passport for user authentication
const passportConfig = require('./config/passport');

require("./controllers/auth-controller.js")(app);

// Listen on port 3000 or assigned port
const server = app.listen(app.get('port'), function() {
    console.log(`App running on ${app.get('port')}`);
});

护照.JS

const passport = require('passport');
const TwitterStrategy = require('passport-twitter').Strategy;

passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: process.env.NODE_ENV === 'production' ? process.env.TWITTER_CALLBACK_URL : 'http://localhost:3000/auth/twitter/callback'
    },
    function(accessToken, refreshToken, profile, done) {
        ...etc, etc, etc

授权控制器.JS

const router = require('express').Router();
const passport = require('passport');

module.exports = function(app) {
    router.get('/twitter', passport.authenticate('twitter'));

    router.get('/twitter/callback',
        passport.authenticate('twitter', {
            successRedirect: '/auth/twittersuccess',
            failureRedirect: '/auth/twitterfail'
        })
    );

    router.get('/twittersuccess', function(req, res) {
        // Successful authentication
        res.json({ user: req.user, isAuth: true });
    })

    router.get('/twitterfail', function(req, res) {
        res.statusCode = 503;
        res.json({ err: 'Unable to Validate User Credentials' })
    })

    app.use('/auth', router);
}

前端代码

帮助者.JS

import axios from 'axios';

export function authUser() {
    return new Promise((resolve, reject) => {
        axios.get('/auth/twitter', {
            proxy: {
                host: '127.0.0.1',
                port: 3001
            }
        }).then(response => {
            resolve(response.data);
        }).catch(err => {
            console.error({ twitterAuthErr: err })
            if (err) reject(err);
            else reject({ title: 'Error', message: 'Service Unavailable - Please try again later.' });
        });
    });
}



更新 我验证了 Passport Authentication 在我的后端端口上工作。我直接在浏览器中调用端点并被重定向到 Twitter 身份验证,然后将新用户返回到我的回调中,新用户保存在我的架构中,该用户保存到会话数据中。

这意味着问题在于在与我的后端不同的端口上使用 Create-React-App。

http://127.0.0.1:3001/auth/twittersuccess

"user": {
    "_id": "redactedbyme",
    "name": "Wesley L Handy",
    "__v": 0,
    "twitterId": "redactedbyme",
    "favorites": [],
    "friends": []
},
"isAuth": true
4

2 回答 2

5

在咨询了几位开发人员并在其他论坛上发布了这个问题后,我找不到手头问题的解决方案。

但是,根据此博客passport-twitter并未针对 RESTful api 进行优化。这个博客提供了一个有用的教程来使用这个 passport-twitter-token策略,react-twitter-auth这里可以找到

这个问题与使用 Create-React-App 应用程序在两台不同的服务器上运行的事实有关,一个用于前端,另一个用于后端。如果没有前端和后端之间的一系列通信,就无法解决 CORS 问题,而护照是不允许的。Passport 是在单服务器上处理 OAuth 的绝佳工具,但在 OAuth 中需要相当多的来回操作,这需要更多的复杂性。

Ivan Vasiljevic的教程是理解和解决这种复杂性的有用起点。

于 2018-01-02T16:31:53.173 回答
0

passport-twitter如果来这里的任何人都无法从策略中使用 Reactjs 获取用户,这就是我找到的解决方案。

您所要做的就是允许凭据

启用凭据可以使用 cookie 或express-session在前端。阅读 MDN 了解更多详情。

后端:

// cors policy setup
app.use(
  cors({
    origin: "http://localhost:3000", // front end url
    optionsSuccessStatus: 200,
    credentials: true,
  })
);

前端:

axios.get(`${apiURL}/profile`, { withCredentials: true })
于 2021-01-05T12:27:18.560 回答