1

Tried 15648070,15648070 and didn't work unfortunately :)

Hi there, first time building an API with Gin, and I'm having some issues setting a cookie on my browser

I mean, when viewing the request on dev tools I see the Set-Cookie header and the correct value, also under Cookie tab within that request I also see the cookie there

The main issue it's not saved on my browser (dev tools -> Application -> Storage -> Cookies and my cookies are not there )

backend :

router.Use(cors.New(cors.Config{
        AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"},
        AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type"},
        MaxAge:           12 * time.Hour,
        AllowAllOrigins:  true,
        AllowCredentials: true,
    }))

    router.POST("/users/login", server.LoginUser)
func (server *Server) LoginUser(ctx *gin.Context) {
        ...
    ctx.SetCookie("access_token", accessToken, 3600, "/", "localhost", false, true)
    ctx.SetCookie("refresh_token", refreshToken, 3600, "/", "localhost", false, true)

    ctx.JSON(http.StatusOK, gin.H{"ok": true, "payload": rsps})

}

frontend :

const login = async () => {
    const res = await fetch("http://localhost:3000/users/login", {
      method: "POST",
      body: JSON.stringify({ username, password }),
    });
    const data = await res.json();
    console.log(data);
  };
  const handleFormSubmit = (e) => {
    e.preventDefault();
    login();
  };

  return (
    <div>
      <h1>Login Page</h1>
      <form onSubmit={handleFormSubmit}>
         ...
        <button type="submit">Login</button>
      </form>
    </div>
  );

Any clue .. ?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Eyal Solomon
  • 470
  • 1
  • 6
  • 15
  • 1
    `fetch` should be called with `mode: 'cors'` and `credentials: 'include'`. If it still does not work, please provide a self-contained demo like https://stackoverflow.com/a/76295116/1369400. – Zeke Lu Jun 09 '23 at 10:08

1 Answers1

0

(Thanks to #Reactiflux channel on Discord)

I was missing 2 things ..

servers side :

  • AllowHeaders headers -> adding "Access-Control-Allow-Headers", "Authorization"

  • Adding AllowOriginFunc -> meaning not allowing * rather a specific domain

frontend side :

  • Adding withCredentials: true to my axios config
Eyal Solomon
  • 470
  • 1
  • 6
  • 15