简体   繁体   中英

Cookies don't get set in chrome via `Set-Cookie` Header

I'm having some trouble setting a cookie through Express.JS in my frontend (Next.JS).

These are the Headers I get back from the API ( /login ):

Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 354
Content-Type: application/json; charset=utf-8
Date: Sun, 21 Mar 2021 19:34:19 GMT
ETag: W/"162-9yg5khk3mdMK+w5SIteR+26LIrw"
Keep-Alive: timeout=5
Set-Cookie: refresh_token=<INSERT REFRESH_TOKEN HERE>; Max-Age=2592000; Expires=Tue, 20 Apr 2021 19:34:19 GMT; HttpOnly
X-Powered-By: Express

This is the code in the Express Backend:

app.post('/login', cookieMiddleware, async (req, res) => {
    try {
        console.log('login now happening');

        if (!req.body.code) throw new Error('no code was provided.');
        const code = req.body.code;

        const data = await fetchToken(
            code,
            CREDENTIALS.REDIRECT_URI,
            CREDENTIALS.CLIENT_SECRET,
            CREDENTIALS.CLIENT_ID,
        );

        res.cookie('refresh_token', data.refreshToken, {
            httpOnly: true,
            maxAge: 30 * 24 * 60 * 60 * 1000,
        });

        res.status(200).json(data);
        res.end();
        return;
    } catch (err) {
        res.status(500);
        res.end();
        return;
    }
});

(I've also tried setting the domain to localhost and the path to everything imaginable)

And this is the cookieMiddleware :

export const cookieMiddleware = (req: Request, res: Response, next: NextFunction): void => {
    const cookies = req.cookies;
    console.log('Cookies: ', JSON.stringify(cookies));

    const signedCookies = req.signedCookies;
    console.log('Signed Cookies: ', JSON.stringify(signedCookies));

    next();
};

In Chrome the cookie doesn't show up, even if I set it as non- httpOnly .

And I always get this in the Console from the Middleware:

Cookies:  {}
Signed Cookies:  {}

EDIT: I've now tested it with Postman and there it works, but still the same result with chrome/via the frontend.

EDIT 2:

I've written the Answer down below, this should fix everything.

I've found the answer

The Problem was cors and the fetch -api.

To set cookies you need to do this in the frontend:

fetch('<DOMAIN>/<PATH>',
    {
        ...
        credentials: 'include',
        mode: 'cors'
    }
)

and this in the backend:

app.use(
    cors({
        credentials: true,
        origin: '<DOMAIN>'
    })
)

BUT YOU MUST GIVE THE BACKEND THE FULL ORIGIN URL , for example:
Your Frontend runs on localhost:3000 and your Backend runs on * localhost:8080 **. This would be your Frontend Code :

fetch('http://localhost:8080/login', {
        ...
        credentials: 'include',
        mode: 'cors'
        ...
    }
)

Then this would be the Backend Code :

app.use(
    cors:({
        credentials: true,
        origin: 'http://localhost:3000'
    })
)

With the same Method you can send the Cookie back to your API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM