Home > OS >  Trouble getting the correct Response Headers
Trouble getting the correct Response Headers

Time:01-11

I'm using axios to send a post request when the user logs in. However, I'm not sure how to get the correct response headers, or rather, I'm seeing different response headers from my console versus what's on my DevTools in Chrome. Here are my codes:

Client

export const login = createAsyncThunk(
    "auth/login",
    async (loginData: LoginData, thunkAPI: any) => {
        try {
            const { email, password } = loginData;
            //config, data, headers, request, status, statusText
            //{ data: resData, headers: resHeaders } 
            const { data: resData, headers: resHeaders } = await axios.post<LoginResponse>(
                "http://localhost:4000/login",
                {
                    email: email,
                    password: password,
                },
            );
            console.log(resData);
            console.log(resHeaders);
            return resData;
        }
        catch (error: any) {
            console.log(error.message);
            console.log(thunkAPI.rejectWithValue(error.message));
            return thunkAPI.rejectWithValue(error.message);
        }
    }
)

Server

    public logIn = async (req: Request, res: Response, next: NextFunction) => {
        const logInData: LogInDto = req.body;
        const user: UserInterface = await this.User.findOne({ email: logInData.email });
        if (user) {
            console.log(user);
            const passwordMatch: boolean = await this.authService.matchPassword(logInData, user);
            console.log(passwordMatch);
            if (passwordMatch) {
                const token: Token = this.authService.createToken(user);
                const cookie: any = this.authService.createCookie(token);
                res.setHeader("Set-Cookie", [cookie]);
                res.status(200).json(
                    {
                        message: "Login success",
                        user: user
                    }
                );
            } else {
                next(new CredentialsException());
            }
        } else {
            next(new CredentialsException());
        }
    }

When I examined the console output for the response versus what's on the Network tab in DevTools on Chrome, I get very different response headers:

DevTools

Console

I have JWT implemented on the server and I'm basically trying to store the cookie on the client so it can be used to authenticate every request.

    public createCookie(token: Token): any {
        return `Authorization=${token.token}; HttpOnly; Max-Age=${token.expiresIn}`;
    }

    public createToken(user: UserInterface): Token {
        const expiresIn: number = 60 * 60; //1hr
        let signOptions: any = {
            expiresIn: expiresIn,
            algorithm: "RS256"
        };
        let payload: TokenPayload = {
            _id: user.id
        };
        return { token: jwt.sign(payload, this.privKey, signOptions), expiresIn };
    }

How can I ensure that I get the Set-Cookie header and store it in my client side?

I'm new to using JWT so any help is greatly appreciated!

CodePudding user response:

This is not an axios problem but an expected browser behavior:

Browsers block frontend JavaScript code from accessing the Set-Cookie header, as required by the Fetch spec, which defines Set-Cookie as a forbidden response-header name that must be filtered out from any response exposed to frontend code.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

Set-cookie is meant for setting cookies in the browser which will later be resent to the server. If you fully rely on cookies for the authorization, you don't have to bother sending them back to the server in your code. The browser will do it for you.

If you want to use JWT authentication, then you should pass the JWT in the response body of the login request. Not in a header.

  • Related