繁体   English   中英

CORS - Facebook - 护照

[英]CORS - Facebook - Passport

我正试图在我的Nodejs / Angular / Express / Passport应用程序中通过Facebook实现OAUTH登录,但我正在努力。

我仍然收到CORS错误:

XMLHttpRequest已被CORS策略阻止:请求的资源上没有“Access-Control-Allow-Origin”标头。 因此,不允许访问“ https://www.xxxxxx.net ”。

虽然我已经添加到我的EXPRESS ROUTER:

router.all('/*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    if ('OPTIONS' === req.method) {
      res.send(200);
    }
    else {
      next();
    }
});

在Developer Console中,我可以看到“oauth / facebook”GET调用的Header正在添加“Access-Control-Allow-Origin”等等。

在Callback中没有'Access-Control-Allow-Origin'等等 - 这是正确的吗?

router.get('/oauth/facebook/',passport.authenticate('facebook',{
      failureRedirect: '/info',
      scope:['email']
  }));

router.get('/oauth/facebook/callback/', passport.authenticate('facebook',{
      failureRedirect: '/info',
      successRedirect: '/',
      scope:['email']
  }),
  function(req,res){
    if(req.user){
      return res.json({token: req.user.generateJWT()});
    } else {
      return res.status(400).json({message:"Not found"});
    }
});

我在此设置中遇到了多次失败,导致此失败。

首先,您需要使用href调用链接“/ oauth / facebook /”:

<a href="/oauth/facebook/" class="btn btn-primary"><span class="fa fa-facebook"></span> Login with Facebook</a>

这可以确保没有角度处理此请求。

它在服务器端调用此路由:router.get('/ oauth / facebook /',passport.authenticate('facebook',{failureRedirect:'/#!/ home',scope:['email']})) ;

哪些回调:

router.get('/oauth/facebook/callback/', passport.authenticate('facebook',{
      failureRedirect: '/#!/info',
      scope:['email']
  }),
  function(req,res){
    if(req.user){
      return res.redirect(303, '/#!/fb/' +req.user.generateJWT());
    } else {
      return res.status(400).json({message:"Not found"});
    }
});

在我的情况下,我还需要返回一个用于登录的令牌:你需要自己处理响应,并将调用重定向到角度侧的自己的'FB'路由,这基本上将我的身份验证密钥带到Angular并登录用户。

跨源资源共享(CORS)机制为Web服务器提供跨域访问控制,从而实现安全的跨域数据传输。

index.js :(服务器)

const cors = require('cors');
..
..
app.use(cors());

有关使用cors的更多信息: npm cors

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM