护照登录和持续会话 [英] Passport login and persisting session

查看:145
本文介绍了护照登录和持续会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景



我有一个具有CRUD功能的MEAN应用程序,并通过邮递员进行了全面测试。我一直在努力坚持登录一段时间,现在没有运气。我已阅读并尝试以下






  • 当这条路线被击中时,我们还可以在控制台中看到用户被序列化。





    那么下一步?



    这是我迷路的地方。我有几个问题。


    1. 用户现在在我的服务器上的会话中?

    2. 我应该将 req.session.passport.user 发送给客户端吗?

    3. 我需要所有未来请求的会话ID ?



    测试会话



    我有第二个路由设置进行测试会话如下

      router.get('/ checkauth',passport.authenticate('local'),function req,res){

    res.status(200).json({
    status:'Login successful!'
    });

    } );

    部分 passport.authenticate('local')(我以为)是在测试用户会话是否存在之前访问该路由,但是即使登录后,我也不会得到200响应。



    这条路线是否期望在头部传递一个 req.session.passport.user 或作为需要auth的http请求的数据参数?



    如果我错过任何内容或理解错误,请告诉我,任何输入都是赞赏的。感谢所有。

    解决方案

    用户现在在我的服务器上的会话中?



    不,您需要在 app.use之前使用 express-session 中间件(passport.session )); 实际将会话存储在内存/数据库中。该中间件负责将Cookie设置为浏览器,并将浏览器发送的Cookie转换为 req.session 对象。 PassportJS只使用该对象进一步反序列化用户。



    我应该将req.session.passport.user发送回客户端吗? / p>

    如果您的客户端在登录时期望用户资源,那么您应该。否则,我没有任何理由将用户对象发送给客户端。



    我是否需要所有未来请求的会话ID?



    是的,对于所有将来的请求,会话ID是必需的。但如果您的客户端是浏览器,则不需要发送任何内容。浏览器会将会话ID存储为cookie,并将其发送给所有后续请求,直到cookie过期。 express-session 将读取该cookie,并将相应的会话对象附加为 req.session



    测试会话



    passport.authenticate('local')用于从POST正文身份验证用户凭据。您应该仅使用此登录路由。



    但是要检查用户是否在所有其他路由中进行身份验证,可以检查 req.user 被定义。

      function isAuthenticated = function(req,res,next){
    if(req.user)
    return next();
    else
    return res.status(401).json({
    error:'User not authenticated'
    })

    }
    router.get('/ checkauth',isAuthenticated,function(req,res){

    res.status(200).json({
    status:'Login successful!'
    });
    });


    Background

    I have a MEAN application with CRUD capabilities fully tested with postman. I have been trying to persist login for quite some time now with no luck. I have read and tried the following

    But I have only been able to register and log a user in, not persist login with a session.

    My App

    Here is a link to the full github repo (if you are looking for the latest changes check develop branch)

    My Understanding of Auth/Login

    Here is my understanding of user login with code examples from my project and screenshot of postman results as well as console logs.

    Passport setup

    I have the following auth.js file, it configs passport

    var passport = require('passport');
    var LocalStrategy = require('passport-local').Strategy;
    
    module.exports = function(app, user){
    
      app.use(passport.initialize());
      app.use(passport.session());
    
      // passport config
      passport.use(new LocalStrategy(user.authenticate()));
    
      passport.serializeUser(function(user, done) {
        console.log('serializing user: ');
        console.log(user);
        done(null, user._id);
      });
    
      passport.deserializeUser(function(id, done) {
        user.findById(id, function(err, user) {
          console.log('no im not serial');
          done(err, user);
        });
      });
    };
    

    This gets called in the server file like

    //code before
    var user    = require('./models/user.js');
    var auth    = require('./modules/auth.js')(app, user);
    // code after
    

    Routing for login

    In my routes I have the login route as follows

    router.post('/login', function(req, res, next) {
    
      passport.authenticate('local', function(err, user, info) {
    
        if (err) {
            return next(err);
        }
    
        if (!user) {
            return res.status(401).json({
                err: info
            });
        }
    
        req.logIn(user, function(err) {
    
            if (err) {
                return res.status(500).json({
                    err: 'Could not log in user'
                });
            }
    
            res.status(200).json({
                status: 'Login successful!'
            });
    
        });
      })(req, res, next);
    });
    

    This route works as tested with postman. I enter the details 'joe' and 'pass' and get the following response.

    When this route is hit we can also see in the console that the user is serialized.

    So what next?

    This is where I get lost. I have a few questions.

    1. Is the user now in a session on my server?
    2. Should I send the req.session.passport.user back to the client?
    3. Do I need the session ID on all future requests?

    Testing the Session

    I have a second route setup for testing the session it is as follows

    router.get('/checkauth', passport.authenticate('local'), function(req, res){
    
        res.status(200).json({
            status: 'Login successful!'
        });
    
    });
    

    The part passport.authenticate('local') (I thought) is there to test if the user session exists before giving access to the route but I never get a 200 response when I run this, even after a login.

    Does this route expect a req.session.passport.user passed in the head or as a data argument on a http request that requires auth?

    If I missed anything or am understanding something wrong please tell me, any input is appreciated. Thanks all.

    解决方案

    Is the user now in a session on my server?

    No, You need to use the express-session middleware before app.use(passport.session()); to actually store the session in memory/database. This middleware is responsible for setting cookies to browsers and converts the cookies sent by browsers into req.session object. PassportJS only uses that object to further deserialize the user.

    Should I send the req.session.passport.user back to the client?

    If your client expects a user resource upon login, then you should. Otherwise, I don't see any reason to send the user object to the client.

    Do I need the session ID on all future requests?

    Yes, for all future requests, the session id is required. But if your client is a browser, you don't need to send anything. Browser will store the session id as cookie and will send it for all subsequent requests until the cookie expires. express-session will read that cookie and attach the corresponding session object as req.session.

    Testing the Session

    passport.authenticate('local') is for authenticating user credentials from POST body. You should use this only for login route.

    But to check if the user is authenticated in all other routes, you can check if req.user is defined.

    function isAuthenticated = function(req,res,next){
       if(req.user)
          return next();
       else
          return res.status(401).json({
            error: 'User not authenticated'
          })
    
    }
    router.get('/checkauth', isAuthenticated, function(req, res){
    
        res.status(200).json({
            status: 'Login successful!'
        });
    });
    

    这篇关于护照登录和持续会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆