Cookie handling in react and expressjs - reactjs

I'm trying to send cookie from the server to the react app and use this cookie as auth in the middleware. With the postman, everything is working, but in the browser, it is not.
As I have read some tutorials I need to set up cors and here is the snippet of my server-side app.
app.use(cors({ origin: "http://localhost:3000/", credentials: true }));
res.status(200).cookie("login_auth", token, { httpOnly: true, domain: "http://localhost:3000" }).json({ user });
Then I'm sending the post request
axios.post("http://localhost:5000/user/login", { email, password }, { withCredentials: true })
but when I check the cookie storage for my app there is no cookie and further, I have no idea how to send the cookie back to the server to fulfill the middleware. In postman it is all done so easily.
I can save the cookie with the "js-cookie", but I don't think it is the right way to do it.
Cookies.set("login_auth", response.data.token);
Somebody help?

Related

I get the cookie from backend, but it is not set in frontend why?

I am using expressjs for backend and vitejs for frontend.
here is my code of backend :
app.use(express.json());
app.use(cors({credentials: true, origin: true, withCredentials: true }))
app.use(cookieParser());
db.query("COMMIT", (err) => {
if (err) return res.status(400).json(err);
const token = createToken(data[0].id, null);
const { password, ...other } = data[0];
return res.cookie("access_token", token, { httpOnly: true, sameSite: 'none', secure: true }).status(200).json(other);
});
frontend code:
await axios.post("http://localhost:8000/user/signup", inputs, { withCredentials: true })
I have tried different browser but it still not working.
If you have different frontend and backend servers (with different hostnames, not just different ports) and the HTML/Javascript served by the frontend server wants to make an HTTP request with cookies to the backend server, this cannot work, because:
Cookies from the backend count as "cross-site" in a request made from the frontend server's page. Such cookies are only sent if they have SameSite=None.
Cookies with SameSite=None must also have the Secure attribute and are then only sent over HTTPS connections.
What you could do:
In your development environment, use HTTP, cookies without SameSite or Secure attributes and have frontend and backend servers both on localhost, just on different ports.
In the production environment, use HTTPS for both frontend and backend servers, cookies with SameSite=None; Secure.

Client does not receive cookies from server, postman does

There is a server, which serves my client react app at root path. So when I make any request to server from POSTMAN, to login for example, cookies are attached perfect. But when I make request from my client using AXIOS and withCredentials field as well, cookies ain't attached, nevertheless the request is sent good, but no cookies received. I don't think there is any reason to search issues in server code, because postman works with it perfect. In case, there is no CORS errors: server provides client app. I get nice response from the server, with no cookies. Postman gets them.
axios request in react app:
export const login = createAsyncThunk(
'auth/login',
async (credentials: ILogin) => {
// todo: making a request to server
const response = await axios({
url: '/api' + '/auth' + '/login',
method: 'POST',
data: credentials,
withCredentials: true,
headers: {
'Content-Type': 'application/json'
},
});
console.log(response)
}
)
Client doesn't receive cookies, neither on localhost nor deployed app.
As you see, only place where cookies are shown it's network section in devtools, but everything else, including server acts like my second request hadn't any cookie, because in this case, server would answer like: agh, already logged in
P.S: i'm using http

Cookies not set on deployed React app on AWS S3

In NestJS i created backend for my app and i used ReactJS for frontend. When i was testing on localhost everything was working fine.
Then i wanted to try and learn some AWS and i made docker image of my backend and deployed it to EC2. After that i got this url:
http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080. If i use this url in Postman and do a POST to my login it works fine. I get back JWT as HttpOnly cookie. In my ReactJS app i replaced localhost links with this new link.
I uploaded my ReactJS app to AWS S3 and got this url http://<bucketName>.s3-website.<Region>.amazonaws.com. If i open this it shows correct first page. The problem comes when i fill login form and click login button the JWT cookie is not set so i get Unauthorized.
I really do not know is the problem in my backend, frontend or in AWS settings.
NestJS controller login function:
async login(
#Body() body: LoginUserDto,
#Res({ passthrough: true }) response: Response,
) {
const data = await this.authService.login(body);
response.cookie('jwt', data, { httpOnly: true });
return 'success';
}
ReactJS code:
const api = axios.create({
baseURL: "http://ec2-<SomeNumbers>.<SomeRegion>.compute.amazonaws.com:8080",
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
});
Thanks!

cookies not saving when using express-session

I am using express-session to save cookies into my browser so I can use it for authentication. I am sending a post request from my frontend (React) using axios to the backend and use User.register to save the new user to the database(mongodb)
I am able to save the user to my database however, there are no cookies being saved in my browser.
Frontend post request using axios:
backend post request handler
In your server add this code
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
Client axios config
const Axios= axios.create({
baseURL: "http://localhost:3001/",
withCredentials: true,
});

Cookie not setting in Scala Play

I am trying to set a cookie from a response when using the scala play framework. I am creating a cookie called session with its value being a UUID (I do know play comes with its own session management).
I can see the response headers contain the set cookie instruction, but the cookie ins't being set.
Below is the scala code in the action in the controller where the cookie is set
val cookie= Cookie("session",
sessionToken,
httpOnly=true,
sameSite=Some(Cookie.SameSite.Lax))
Ok(Json.toJson(res))
.withCookies(cookie)
// Also tried with .bakeCookies() after the withCookies() call
I can see the cookie header in the response in both FireFox and Chrome. They both show what appears to be a correctly formed cookie in their respective response cookie viewer in their developer tools.
Set-Cookie: session=c0174ed1-ebd3-4a8d-a5b2-5b09a3fe616b; SameSite=Lax; Path=/; HTTPOnly
However, in both browsers the cookie does not get set. I have tried true and false httpOnly, and messing with the maxAge value. I have tried setting the domain to a url and then setting the url in the hosts file as suggested here.
The URL on the react frontend is
http://localhost:49161/login/hydrate
and the endpoint in play is
http://localhost:49162/user/login/rehydrate
I did also try setting the path to /login/hydrate/ on the cookie
The react code on the front end
// Inside async function
// methodStrings[method] = "post" in this request
axios[methodStrings[method]](url, params)
.then(result => {
resolve(result);
})
.catch(err => {
console.error(`Error with request to ${url} - ${err}`);
reject(err.response.status);
});
And then I console.log the result from awaiting the request
Problem is in axios (and/or browser).
Based on this issue Cookies headers are present but Cookies are not stored in browser #1553 you need to set withCredentials Axios config to store cookies in browser after request:
axios.post('domain.com', {
name: 'name',
password: 'password'
}, {
//AxiosRequestConfig parameter
withCredentials: true //correct
})

Resources