Ошибка CORS с использованием стратегии Passport LinkedIn - PullRequest
1 голос
/ 02 октября 2019

Таким образом, я использую passport.js и стратегию passport-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;

Теперь, в моей консоли разработчика, у меня есть

  1. URL-адреса перенаправления: http://localhost:3000/api/auth/linkedin/callback
  2. Домены: http://localhost:3000, http:localhost:3000/api/auth/linkedin

Может кто-нибудь сказать, где яидет не так? Я знаю, что ошибка CORS происходит, когда маршрут не находится в белом списке, но у меня есть эти белые.

Спасибо.

1 Ответ

0 голосов
/ 02 октября 2019

Добавьте следующий код в ваш 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");
});
...