How to pass data with a session or cookie while redirecting with express / nodejs / passport?

Viewed 671

See previous question: How to pass data along with redirect using express?

My issue is that I've got a Reactjs SPA and a NodeJS/Express/Passport backend. The express backend is sending a res.redirect(%url%) but I cannot send additional information securely along with that redirect.

The answer to the previous question was "send a cookie or send the data in a session". How can this be done?

My code as it currently stands:

samlRouter.use(session(config.session));
samlRouter.use(passport.initialize());
samlRouter.use(passport.session());

samlRouter.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', req.header('origin'));
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-Width, Content-Type, Accept, Authorization');
    res.header('Access-Control-Allow-Credentials', 'true'); //SAML

    if (req.method == 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT, POST, GET');
        return res.status(200).json({})
    }
    next();
})

samlRouter.post('/login/callback',
    (req, res, next) => {
        passport.authenticate('saml', config.saml.options)(req, res, next)
    },
    (req, res, next) => {
        console.log('req.user.nameID :>> ', req.user?.nameID);   // ***THIS IS CORRECT**
        req.session.user = req.user;

        return res.redirect(`${req.body.RelayState}`);
    });

The problem is - I need to tell the front-end reactjs application who the req.user.nameID is. I can't just put it in a query string on the redirect because it's the login (and thus anyone that wanted to just type in xxxx.com/privatePage?myusername could pretend to be me). It's my understanding the other options are 'set a cookie' and 'use the session'.

How, specifically, can I implement one of these two other options to securely pass data to my front end after authentication? (the second to last line of the code block above).

EDIT: worth noting that my API server and my Front-end file host are different -- so I'll need a cross-site solution. Certainly there are systems that use third-party authentication systems that I can emulate.

2 Answers

anyone that wanted to just type in xxxx.com/privatePage?myusername could pretend to be me

Cookies won't solve this problem. Users can just as easily set cookies.

If you want examples of how authentication and authorization credentials can be securely passed to public clients read up about the OAuth 2.0 authorization code grant, that is exactly the problem it solves.

Related