gogorilla

Golang Mux Router CORS Error when Adding Credentials to Request


I simply need to allow for credentials in my Go Mux router. It seems like it should be pretty straight forward. As soon as I set withCredentials to true in my axios interceptor, I only get CORS errors. However, I believe I configured it correctly. Is there something I'm missing?

Here's where I serve the routes:

log.Fatal(http.ListenAndServe(":8080",
handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type", "Authorization", "withCredentials"}), 
handlers.AllowedMethods([]string{"GET", "POST", "PUT", "HEAD", "OPTIONS"}),
handlers.AllowedOrigins([]string{"*"}), 
handlers.AllowCredentials())(loggedRouter)))

Obviously, I need to enable this to set and get cookies. I attempt to set the cookie this way:

//set session cookie
http.SetCookie(w, &http.Cookie{
    Name:     "session_key",
    Value:    staffAdminSession.SessionKey,
    Expires:  time.Now().Add(time.Hour * 24),
    HttpOnly: true,
})

It sets in postman, but not in Chrome. It must be a CORS/request header issue.

Here's all the information I'm given for the error - the status of the request is CORS Error: enter image description here


Solution

  • You should check the error message in the console. There should be an error message like this:

    Access to fetch at 'http://0.0.0.0:8081/login' from origin 'http://localhost:8080' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

    The screenshot shows that the origin is http://0.0.0.0:3000, try replacing

    handlers.AllowedOrigins([]string{"*"}
    

    with:

    handlers.AllowedOrigins([]string{"http://0.0.0.0:3000"}