Issue
I am creating a project for school, and I need to create a backend in spring boot and a frontend in vanilla JS +HTML+ CSS. Since both are on localhost but on different Origins namely on port 8080/5500 respectively ,I am having some issues with CORS in that my cookies are not saved in the browser so no session is created between backend and frontend. This leads to the problem that after login in I will not be able to access securised endpoints because it will require me to log in again since no session is established.
What solution do I have for making this work / saving the cookies?
Further I will give several details and images about the issue that I have.
The backend uses MySQL, spring boot and RestControllers. It basically is a simple CRUD that I also added spring security to. Now this is how my Spring Config looks like
and this is how my CORS config looks like
and this is how my fetch request looks like in the frontend. Also the request to /save
The flow is as follows : I make a request to /login, than I should be able to use the /save endpoint. This works flawlessly on postman since accessing /save works only after /login was successfully otherwise I get unauthorized, but it does not work in the browser because the cookie that is send with the first response is not saved as below. In the following image the response provides the JSESSION cookie after successfully authentication.
But then when I check cookies section, the cookie is not there.
And when I make a request to the /save endpoint I get the following issue
I also tried the answer over here How to set cookie domain and path with Spring boot but cookies are still not saved.
Solution
The browser refuses to allow a URL whose host is [::1]
to set a cookie with a Domain
attribute of 127.0.0.1
. Why? Simply because, even though [::1]
is the IPv6 equivalent of 127.0.0.1
, the latter doesn't domain-match the former.
Anyway, why would you want to set a cookie with an IP address for the Domain
attribute? You seem to be misunderstanding the purpose of that attribute; read what the MDN Web Docs page entitled Using HTTP Cookies has to say about it:
The
Domain
attribute specifies which hosts can receive a cookie. If unspecified, the attribute defaults to the same host that set the cookie, excluding subdomains. IfDomain
is specified, then subdomains are always included. Therefore, specifyingDomain
is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about a user.
In your case, the host of the URL that sets the cookie is an IP address and not a domain. Therefore, specifying a Domain
attribute for that cookie is pointless, simply because an IP address doesn't have subdomains.
Answered By - jub0bs
Answer Checked By - Clifford M. (JavaFixing Volunteer)