how to redirect to original page after successful authentication using passport-google-oauth

后端 未结 2 515
日久生厌
日久生厌 2021-01-06 13:09

I am using node passport-google-oauth module and trying to redirect the page back to the original path after successful authentication using a session based approached sugge

2条回答
  •  生来不讨喜
    2021-01-06 13:21

    Can also store the first URL in the session, only if the variable is currently not set. Then post login if this var is set, then re direct to that.

    This is better than a header which might not be accurate from a 3rd party oauth.

    In Java I would do it in a filter (check for a session variable to, say redirect_to or first_url, if its null then set it, if not the login/ sign up page). In node js can use middleware as explained in https://stackoverflow.com/a/13336055/1643558

    Quoting that answer: I have a middleware I use with app.get('/account', auth.restrict, routes.account) that sets redirect_to in the session...then I redirect to /login

    auth.restrict = function(req, res, next){
        if ( !req.session.userid ) {
            req.session.redirect_to = '/account';
                res.redirect('/login');
        } else {
            next();
        }
    };
    

    Then in routes.login.post I do the following:

    var redirect_to = req.session.redirect_to ? req.session.redirect_to : '/';
    delete req.session.redirect_to;
    //is authenticated ?
    res.redirect(redirect_to);
    

提交回复
热议问题