ethan0905 / ft_transcendence

Wiki with step-by-step explained strategy on how to: create app (front+back+infra), 42auth, 2FA and more..
2 stars 0 forks source link

TypeError: Cannot read properties of undefined (reading 'token') #22

Closed ethan0905 closed 1 year ago

ethan0905 commented 1 year ago

Hello I have an error when trying to use my cookie informations.

When i try to read content from my backend side,

const token: string = req.cookies["token"]; // tried also this: const token: string = req.cookies.token;

an error occure. My token is considered empty or undefined, even if I know that it not the case.

backend_nestjs    | [Nest] 1076  - 03/30/2023, 5:04:12 PM   ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'token')
backend_nestjs    | TypeError: Cannot read properties of undefined (reading 'token')
backend_nestjs    |     at AuthService.enable2FA (/app/src/auth/auth.service.ts:311:36)
backend_nestjs    |     at AuthController.enable2FA (/app/src/auth/auth.controller.ts:89:29)
backend_nestjs    |     at /app/node_modules/@nestjs/core/router/router-execution-context.js:38:29
backend_nestjs    |     at processTicksAndRejections (node:internal/process/task_queues:95:5)
backend_nestjs    |     at /app/node_modules/@nestjs/core/router/router-execution-context.js:46:28
backend_nestjs    |     at /app/node_modules/@nestjs/core/router/router-proxy.js:9:17

If you already have manipulated cookies or have any idea, feel free to answer.

ethan0905 commented 1 year ago

Tried to use packages to make the read of cookies easier (cookies-js), but still, my token var remains undefined.

import Cookies from 'js-cookie';

// [...]

const token = Cookies.get('token');
ethan0905 commented 1 year ago

After a lot of researches, the cookie was well stored, but the parameters were blocking the cookie retrieve aspect on client side (for security concerns).

Check if the cookie is HttpOnly: If the cookie is set with the HttpOnly flag, it cannot be accessed from client-side JavaScript. In this case, you will need to find a way to retrieve the cookie on the server-side.
    async createCookies(@Res() res: Response, token: any) {
        console.log("Creating cookies with: [" + token.access_token + "]\n");
        const cookies = res.cookie("token", token.access_token,
        {
          expires: new Date(new Date().getTime() + 60 * 24 * 7 * 1000), // expires in 7 days
        //   httpOnly: true, // for security
          httpOnly: false, // setting it to false allows me retrieve it on the client side
        });
    }