Home  >  Article  >  Backend Development  >  Browser does not save cookies sent by Golang backend

Browser does not save cookies sent by Golang backend

PHPz
PHPzforward
2024-02-14 23:30:091098browse

Browser does not save cookies sent by Golang backend

php editor Strawberry is here to introduce to you a problem about browsers saving cookies. Sometimes when we use the Golang backend to send cookies, we find that the browser does not save them. This may be due to a number of reasons, such as browser privacy settings or some issues in the code. In this article, we will explore this issue in detail and provide some solutions to ensure that browsers correctly save cookies sent by the Golang backend. let's start!

Question content

I know this question has been asked many times, but I tried most of the answers and still can't get it to work.

I have a golang api with net/http package and js frontend. I have a function

func setcookie(w *http.responsewriter, email string) string {
    val := uuid.newstring()
    http.setcookie(*w, &http.cookie{
        name:     "gocookie",
        value:    val,
        path:     "/",
    })
    return val
}

This function is called when the user logs in and I want it to be sent to all other endpoints. This is consistent with postman's expectations. However, when it comes to the browser, I can't seem to get it to remember the cookie or even send it to other endpoints.

js example using endpoint

async function getDataWithQuery(query, schema){
    
    let raw = `{"query":"${query}", "schema":"${schema}"}`;
    let requestOptions = {
        method: 'POST',
        body: raw,
        redirect: 'follow',
    };
    try{
        let dataJson = await fetch("http://localhost:8080/query/", requestOptions)
        data = await dataJson.json();
    }catch(error){
        console.log(error);
    }

    return data;
}

I have tried setting the samesite attribute in golang, or using credential: "include" and other answers in js, but without success.

Solution

Thanks to the discussion in the comments, I found some tips about this problem.

Save cookies (api and frontend are on the same host)

I use document.cookie to save cookies. I set the options manually because calling res.cookie on the response from api fetch only returns the value. An example is document.cookie = `gocookie=${res.cookie};path=/;domain=localhost;.

Send cookie

This question has been answered in a previous question and again in the comments. The problem was that I used credential:'include' instead of the correct credentials:'include' (plural).

cors and cookies

If the api and frontend are not on the same host, you will have to modify both the api and the frontend.

front end

The cookie must have the domain of the api, since it is the api that requires it, not the frontend. So for security reasons you cannot set cookies for a domain (api) of another domain (frontend). The solution is to redirect the user to an api endpoint that returns the set-cookie header in the response headers. This solution instructs the browser to register the cookie with an additional domain (the api's domain, since the api sent it).

Also, you still need to include credentials:'include' on the frontend.

api

You need to set some headers. What I set is

    w.header().set("access-control-allow-origin", frontendorigin)
    w.header().set("access-control-allow-credentials", "true")
    w.header().set("access-control-allow-headers", "content-type, withcredentials")
    w.header().set("access-control-allow-methods", method) // use the endpoint's method: post, get, options

You need to expose the endpoint where the frontend will redirect the user and set a cookie in the response. You can omit it and instead of manually setting the api's domain, the browser will automatically populate it with the domain.

To handle cors and let js successfully send the cookie, you must set the samesite=none and secure attributes in the cookie and provide the api over https (for simplicity, I use ngrok).

like this

func SetCookie(w *http.ResponseWriter, email string) string {
    val := uuid.NewString()
    http.SetCookie(*w, &http.Cookie{
        Name:     "goCookie",
        Value:    val,
        SameSite: http.SameSiteNoneMode,
        Secure:   true,
        Path:     "/",
    })
   // rest of the code
}

I recommend you also read the difference between using localstorage and document.cookie, this was one of the issues I had.

Hope this helps.

The above is the detailed content of Browser does not save cookies sent by Golang backend. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete