I'm sending a HTTPOnly cookie with JWT from server(node/express) to client(vue), and the browser doesn't store the cookie, I have tried with three different browsers chromium Brave and Firefox (just in case lol), in Firefox with DEV Tools -> Network -> cookies tab I can see the token is sent, but the browser never stores it.
I'm in localhost...
const token = jwt.sign(
{
id: newUser._id
},
process.env.JWT_SECRET,
{
expiresIn: process.env.JWT_EXPIRES_IN
}
);
if (process.env.NODE_ENV === 'production') cookieOptions.secure =
true;
const cookieOptions = {
expires: new Date(
Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60
* 1000
),
httpOnly: true
};
res.cookie('jwt', token, cookieOptions);
The whole point of httpOnly cookies is to not be visible to browser-based scripts. So the browser stores them, but doesn't share them with scripts it runs.
Related
in my express i use res.cookie to post a cookie
res.cookie("jwt", token, {
expires: new Date(Date.now() + process.env.COOKIEEX * 24 * 60 * 60 * 1000),
withCredentials: true,
httpOnly: false,
});
res.status(200).json({
status: "success",
user,
token,
});
but when i send a req to that middleware from my react app using axios i find the cookie in the network > headers> set-cookie , but its not sets in the browser:
<form
onSubmit={async (e) => {
e.preventDefault();
const res = await axios.post(
"http://127.0.0.1:3000/api/v1/users/login",
{
email: "na#test.test",
password: "password#",
},
{ credentials: true }
);
}}
>
i also tried to set samesit=None and secure, its works and i can see the cookie in the browser but after refreshing the page it disappears :
res.cookie("jwt", token, {
expires: new Date(Date.now() + process.env.COOKIEEX * 24 * 60 * 60 * 1000),
withCredentials: true,
httpOnly: false,
sameSite:"None",
secure:true
});
Browsers are less and less likely to include cookies over HTTP, instead you should try to only use HTTPS when a browser is involved.
Samesite=none;secure only works over HTTPS and will not be included in requests over HTTP. When you don't include any samesite, the default is then set to Lax (I think) and that means that it will not be included in POST requests to a different site. To do cross-site requests with cookies, you need to set samesite=none;secure and use HTTPS.
As far as I know, when you work with cookies, the backend (express in your case) handle the settings of the cookies in your browser [SESSION], in an another word, you just need to set { credentials: true } in your frontend app, the token that was saved on your browser is logically saved in your DB, so whenever a request coming, there is a check on the DB if the two tokens matches [ the one coming from the req and the one is saved on your DB ].
So mainly, or again as I know it's not gettable in other word if you just need something which is included in your token, just send it explicitly.
Why am i getting a authorization header when i send the requests to / from the client but when i send requests to /auth/signup on the same origin i'm not getting the authorization headers.
Here is how i'm setting my cookie in the browser so that i will send them as a header from the browser.
export const storeRefreshToken = (res: Response, token: string): void => {
// Invalidate old tokens
res.cookie(__cookieName__, token, {
httpOnly: true, // they can not be accessed using javascript
path: "/",
sameSite: "lax",
});
};
I'm using jwt authentication and graphql, I'm getting the headers when i'm at / but if i change to /auth/signin I'm not getting anything. What may be posibly the problem when setting cookies.
I am unable to retrieve a cookie that I sent earlier.
As part of login, I sent back a refresh token as an httpOnly cookie.
const payload = {name, email};
console.log("payload: ", payload);
const accessToken = jsonwebtoken.sign(payload, process.env.ACCESS_TOKEN_KEY, { expiresIn: '15m' });
const refreshToken = jsonwebtoken.sign(payload, process.env.REFRESH_TOKEN_KEY, { expiresIn: '1d' });
console.log("Access Token:", accessToken); // access token is generated
console.log("Refresh Token:", refreshToken); // refresh token is generated
res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: false, sameSite: 'Lax', maxAge: 24*60*60*1000 }); // call succeeded. what is the name of cookie?
res.json({ accessToken });
Later on a refresh endpoint I look for a cookie and can't find it:
export const handleRefreshToken = async (req, res) => {
console.log("Request Cookies", req.cookies);
const cookies = req.cookies;
if (!cookies?.refreshToken) return res.sendStatus(401);
I see the following cookies:
_ga: 'xxxxxxxxxxxxxxxxx',
_gid: 'xxxxxxxxxxxxxxxx',
_gat_gtag_UA_xxxxxx: 'x',
_ga_QPY49S2WC4: 'xxxxxxxxxxxxxxxxxxx'
This is on my dev environment with nodejs running on localhost:5000.
Update: Using devtools (Network) I see the cookie in the response on the client side. The name of the cookie is 'refreshToken'. However, the cookie doesn't show up on the browser when I look at the cookies on the browser. Perhaps, the cookie isn't being retained on the browser. Any suggestions on why that could be?
Update2: The link provided by #Konrad Linkowski worked. When the axios request is made from the client, I needed the option "{ withCredentials: true }".
The error was on the client end. The express code functioned correctly. This link explains it: Does Axios support Set-Cookie? Is it possible to authenticate through Axios HTTP request?
My original call on the client side (using axios) was:
const res = await axios.post('/login', { ident: email, password });
Instead it should have been:
const res = await axios.post('/login', { ident: email, password }, { withCredentials: true });
I am in a weird situation where cookie is not getting set in browser and in response its showing in browser
Response Screenshot from Network Tab
React Application Running on Domain - https://2367cc15b.eu.ngrok.io
Node Js Running On Domain - https://e17b14c2835b.ngrok.io
Code to set cookie
res.cookie('holofyKey', holofyKey, { httpOnly: true, domain: '.ngrok.io', expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)) });
I am using app.use(cookieParser()); in my middleware.
Is there something i am missing ?
PS - I tried with removing httpOnly and domain name from options still no luck
After 2 days trying every possible solution this finally worked for me
This is how you need to call the api from which you want to set the cookie.
const postHelper = async (url, body) => {
return await fetch(url, {
method: "POST",
headers: {
Accept: "applicaiton/json",
"Content-Type": "application/json",
},
body: body && JSON.stringify(body),
withCredentials: true, // should be there
credentials: 'include' // should be there
});
};
After adding this you will get CORS error so please add this line of code in your server
app.use(cors({ origin: true, credentials: true }));
And finally
res.cookie('cookieKey', cookieKey, { expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365)), secure: true });
PS - This solution will work in case of Cross domain and same domain but in case of cross domain most browsers will not allow you to set cookie until user agree.
For the authentication my server (nestjs) sends back a cookie with the token.
This is done like this:
#SetCookies()
#Post("account/signin")
async signin(#Body() dto: LoginDto, #Req() req, ){
const token = await this._authService.signin(req.user);
const options: CookieOptions = {
expires: moment().add(10, "days").toDate(),
signed: false,
secure: false,
sameSite: false,
httpOnly: true,
};
req._cookies = [
{
name: "SESSIONID",
value: token,
options: options,
}
];
}
And it works! At least postman shows me that the cookie was successfully created and send back.
But when Angular calls the API like this:
public signin(dto: LoginDto): Observable<any>{
return this._httpClient.post("http://localhost:3000/account/signin", {
username: dto.username,
password: dto.password,
}, {
withCredentials: true,
})
}
The set-cookie is send back visible in the network tab of the devtools.
Chrome devtools response headers
But the cookie is not stored in on the disk. The user is logged in but no cookie is persisted. EditThisCookie shows nothing and after a reload no cookie is send when a request to the server is made.
In other questions the problem got resolved by setting the secure attribute of the cookie to false, which i already tried.
I have setup cors with credentials = true on the server, without any errors on both sides while signing in.