代码之家  ›  专栏  ›  技术社区  ›  Valentin Macé

Ionic+Passport isAuthenticated()返回false

  •  0
  • Valentin Macé  · 技术社区  · 8 年前

    我的应用程序在angularJs 1.6中构建,MEAN stack运行良好,我使用passport进行身份验证。

    当我决定用ionic测试它时,应用程序本身运行良好(文件基本相同),但passport的身份验证被破坏

    我可以注册和登录用户,但当我想检查用户是否使用req登录时。isAuthenticated()在我的服务器上,它总是回答false。

    我想这是因为当我从我的普通angular应用程序发出请求时,请求中包含一个带有密码和电子邮件的用户对象,但当我从我的ionic应用程序发出请求时,用户不见了

    Difference between the two requests

    我花了一天的时间在这上面,任何帮助都会很好!

    编辑1:

    抱歉没有包括代码,这是我第一次来这里

    我的登录路径+我的登录功能

     app.post('/api/login', login);
    
    function login(req, res, next) {
    //console.log(req);
    passport.authenticate('local-login', function(err, user, info) {
      if (err) {
        return next(err); // will generate a 500 error
      }
      // Generate a JSON response reflecting signup
      if (! user) {
        return res.send({success : 'false', message : req.flash('loginMessage') });
      }
    
      req.login(user, function(err) {
        if (err) { return next(err); }
          //console.log(req);
        return res.send({success : 'true', message : req.flash('loginMessage') });
      });
    
    })(req, res, next);
    }
    

    问题是,req。登录被执行,我获得了成功:是的,但在爱奥尼亚/cordova应用程序中,似乎什么都没有被记住

    之后,当我试图检查用户是否使用此

      app.get('/api/login/loggedin', function(req, res) {
        res.send(req.isAuthenticated() ? req.user : '0');
      });
    

    我总是得到“0”,我认为这是因为cordova/ionic应用程序不能使用cookie(请求之间的区别也是ionic应用程序中缺少cookie),但我不明白如何管理一个既适用于我的web angular应用程序,又适用于其ionic版本(仍适用于passport)的解决方案

    1 回复  |  直到 8 年前
        1
  •  0
  •   Valentin Macé    8 年前

    我刚刚找到的解决方案:

    事实上,这是CORS的问题,因为我不知道确切的原因,但爱奥尼亚/科尔多瓦没有把 {user:...} 帖子请求中的信息

    简单地加上

    var cors = require('cors');
    app.use(cors({origin: 'http://localhost:8100', credentials: true}));
    

    对于您的服务器,它允许req包含所需的信息

    加上

    {withCredentials: true}
    

    发送到所有将使用isAuthenticated()检查的请求。例如:

    $http.get('http://localhost:8081/api/todos', {withCredentials: true});
    

    所以发送的请求包含{user:…}部分

    我不知道为什么你需要在客户端和服务器端都授权它,但它工作得很好

    推荐文章