Search code examples
ajaxgocorsjwtsetcookie

When I do POST request on golang api using POSTMAN I successfully receive the jwt token as a cookie but when I do it from browser I get no cookie


I have made an API in golang. Backend and frontend are running on separate servers. When I test the API with POSTMAN everything works fine and I receive the cookie containing the jwt token but when I do the request from the frontend then no cookie is received.

Here is the middleware for handling CORS:

func corsHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // origin := r.Header.Get("Origin")
        w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5000")
        if r.Method == "OPTIONS" {
            w.Header().Set("Access-Control-Allow-Credentials", "true")
            w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")

            w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, Authorization, access-control-allow-origin")
            return
        }
        h.ServeHTTP(w, r)
    })
}

Following is the cookie generator:

    jwtCookie := &http.Cookie{
        Name:   "jwtToken",
        Secure: false,
        HttpOnly: true,
        Value:    tokenString,
        Expires:  expiryTime,
    }

    http.SetCookie(w, jwtCookie)
    w.Header().Add("Access-Control-Allow-Credentials", "true")
    w.WriteHeader(http.StatusOK)

Following is the ajax request:

       $.ajax({
            type: 'POST',
            url: 'http://localhost:8080/api/signin',
            data: JSON.stringify({
                "username": $('#username').val(),
                "password": $('#password').val()
            }),
            xhrFields: { withCredentials: true },
            contentType: "application/json",
            dataType: "json",
            success: function(data) {
                console.log(data);
            },
            error: function(message) {
                console.log(message.responseJSON);
            }
        });

In firefox the response header looks like this: As you can see in image 1, the cookie is received in header but it is not visible in storage

In chrome the response header looks like: there is no cookie visible in chrome

I am stuck on this for quite a long time. Any help would be valuable :)


Solution

  • I had to add w.Header().Add("Access-Control-Allow-Credentials", "true") for all the requests and not just OPTIONS preflight request and also it turned out that chrome was not showing the cookie in storage but it was present and working as expected, later I checked in firefox and the cookie was visible in storage.