【问题标题】:CORS error with Passport LinkedIn StrategyPassport LinkedIn 策略出现 CORS 错误
【发布时间】:2020-01-31 22:59:36
【问题描述】:

所以我使用passport.jspassport-linkedin-oauth2 策略通过链接登录。

但我一直遇到这个错误:

Access to XMLHttpRequest at 'https://github.com/login/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fapi%2Fauth%2Fgithub%2Fcallback&client_id=Iv1.56db9f8a973882db' (redirected from 'http://localhost:3000/api/auth/github/') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在,这就是我的 passport-config.js 文件的样子:

var LinkedInStrategy = require('@sokratis/passport-linkedin-oauth2').Strategy;

module.exports = function(passport) {
passport.use(new LinkedInStrategy({
    clientID: 'some client id',
    clientSecret: 'some client secret',
    callbackURL: "http://localhost:3000/api/auth/linkedin/callback",
    profileFields: [ 'id', 'email-address'],
  }, function(accessToken, refreshToken, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      console.log(JSON.stringify(profile))
      return done(null, profile);
    });
  }));
}

我的 router.js 文件如下所示:


// imports and other code

router.get('/linkedin',
  passport.authenticate('linkedin', { scope: ['r_emailaddress', 'r_liteprofile', ''] }))

router.get('/linkedin/callback', passport.authenticate('linkedin', {
  successRedirect: '/',
  failureRedirect: '/login'
}));

module.exports = router

在我的 app.js 中我写过:

// all the above code
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var engine = require('consolidate');
var passport = require('passport')
var cors = require('cors')
var app = express();
var auth = require('./routes/auth');
var home = require('./routes/home');

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/noq-se', { promiseLibrary: require('bluebird') })
  .then(() =>  console.log('connection successful'))
  .catch((err) => console.error(err));


app.set('views', __dirname + '/public/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html')

app.use(logger('dev'));
app.use(function(req, res, next) {
  var allowedOrigins = ['http://localhost:8080'];
  var origin = req.headers.origin;
  if(allowedOrigins.indexOf(origin) > -1){
    res.setHeader('Access-Control-Allow-Origin', origin);
  }
  // res.header('Access-Control-Allow-Origin', 'http://localhost:8080/');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', true);
  return next();
});
app.use(cors())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
app.use(express.static(path.join(__dirname, 'dist')));

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

app.use('/api/auth', auth);
app.use('/', home);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// restful api error handler
app.use(function(err, req, res, next) {
  console.log(err);

  if (req.app.get('env') !== 'development') {
      delete err.stack;
  }

    res.status(err.statusCode || 500).json(err);
});

module.exports = app;

现在,在我的linkedin 开发者控制台中,我有

  1. 重定向网址: http://localhost:3000/api/auth/linkedin/callback
  2. 域: http://localhost:3000, http:localhost:3000/api/auth/linkedin

谁能告诉我哪里出错了?我知道当路由未列入白名单时会发生 CORS 错误,但我确实将这些列入白名单。

谢谢。

【问题讨论】:

    标签: javascript node.js express oauth passport.js


    【解决方案1】:

    将以下代码添加到您的 app.js

    app.all('/*', function(req, res) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    });
    

    【讨论】:

    • 这样做不会引发错误,但什么也不会发生。
    • 您能否详细说明一下什么也没发生,您是否收到任何日志/数据/其他错误?
    • 好吧,没有发生任何事情是由于其他原因。 CORS 错误仍然存​​在
    • 我也尝试实现 Github 策略,但我一直收到同样的错误。
    • 我应该已经指定了,您需要在调用任何 app.use(...) 之前输入此代码
    猜你喜欢
    • 2020-03-24
    • 2021-05-28
    • 2015-08-16
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    • 2020-03-12
    • 1970-01-01
    相关资源
    最近更新 更多