bradtraversy / proshop-v2

ProShop ecommerce website built with MERN & Redux Toolkit
532 stars 267 forks source link

Issue with Placing Order: Authentication Error (401) and Missing JWT Cookie #7

Closed khantseithu closed 1 year ago

khantseithu commented 1 year ago

Description: I am currently experiencing difficulties while following the course in the "Placing Order" section. Whenever I attempt to place an order, I encounter a "401 - Not authorized, no token" error, which appears to be related to authentication (refer to Image 1).

While I am able to successfully log in to the client, it seems that the JWT (JSON Web Token) cookie is not being set on the client after logging in (see Image 2). However, when I log in using Postman solely on the backend, the JWT cookie is successfully sent back (refer to Image 3).

To provide more context, I have shared the relevant images and code snippets below:

Image 1: image

Image 2: image

Image 3: image

You can access my code repository here: TechMart

Upon reviewing the situation, I suspect that the error is caused by the absence of the JWT on the client side. Consequently, when I attempt to place an order, the protect middleware interferes.

I kindly request assistance in resolving this issue as I have been stuck on it for quite some time. If you are able to identify a solution, please feel free to submit a pull request to my repository.

Thank you for your attention and support.

Sincerely, Khant Sithu

bushblade commented 1 year ago

Hi @khantseithu Is this an issue with your own project and are you following the course? Or is this an issue you are experiencing with cloning and running the repository code?

bushblade commented 1 year ago

I just took a look at your code. Your issue is here And the fact you are using cors middleware. This in combination with using samesite cookies is conflicting. localhost:3000 where your client is running is a different origin to where your backend is running. I see you are using the cors middleware to get around that (though your really should configure it to respond only to your client). But by making the request cross origin i.e. from localhost:3000 to your backend url, then those are two different domains, so cookies marked as sameSite: 'strict' will not go along for the ride and so no token is included in the request. If you are following the course on either Brad's platform or Udemy then please make sure to post in the comments or Q&A or Discord server. I'll close as an issue here as this seems to be your own implementation and not an issue with the project code.