How to estabilish express session with passport.js trough multiple APIs

Viewed 90

nodejs newbie here. Currently i'm working on implementing local authentication via passport.js for admin user. I have the following setup: web client for admin, api for admin, and service api.

So the call for auth is goes like this:

clientAdmin > apiAdmin > serviceApi (auth) > apiAdmin > clientAdmin.

However, express-session is not working properly on this setup, its just doesen't store passport in session and never runs deserializeUser function. I assume that when serviceApi responds to apiAdmin, its trying to store a cookie in it, but apiAdmin can't store it.

What shall i do to get the cookie from response on apiAdmin side, and then pass it to the client? Or maybe i can kinda resend the response that i get from serviceApi to client?

P.S. If i do a call directly from client to service, ignoring adminApi, all works fine, so my middleware and passport config are configured properly. But i need to implement a setup with 2 apis.

Function on client that calls adminapi

const login = () => {
    axios({
        method: "POST",
        data: {
            username: username,
            password: password,
        },
        withCredentials: true,
        url: config.loginURL,
    }).then((res) => {
        if (res.data.userId) {
            setUser({ id: res.data.userId });
        }
    });
};

Function on adminapi that calls serviceapi

loginHandler(req: express.Request, res: any) {
    axios({
        method: "POST",
        data: req.body,
        withCredentials: true,
        url: config.loginURL,
    })
        .then((response) => {
            res.send(response.data);
        })
        .catch((err) => console.error(err));
}

Function on serviceapi

loginHandler(req: any, res: any, next: express.NextFunction) {
    
    passport.authenticate("local", (err, user) => {
        if (err) throw err;
        if (!user) res.json({ message: "Invalid credentials" });
        else {
            req.logIn(user, (err: Error) => {
                if (err) throw err;
                res.json({ message: "Authorized", userId: user.id });
            });
        }
    })(req, res, next);

}
0 Answers
Related