Cookie Not Created?[SOLVED]

Writing a function to serve JSON Web Token as the value of a cookie, but though the code executes without error I am not getting the cookie created in my browser.

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"name":  u.Name,
		"email": u.Email,
		"exp":   time.Now().Unix(),
	})

	authToken, err := token.SignedString([]byte("secret"))
	if err != nil {
		log.Panic(err, os.Stdout)
	} else {
		cookie := http.Cookie{Name: "access_token", Value: authToken, MaxAge: 0}
		http.SetCookie(w, &cookie)
	}
}

Not sure if I’m doing something wrong with the way I’m trying to serve the cookie or not. Any help is appreciated :slight_smile:

nit, this doesn’t do what you think it does.

Can you show more code? It looks like this is part of a larger function that eventually writes a response back to the client.

Its a utility function prototype/proof of concept

// ServeToken creates JSON Web Token with user claims and attaches it to Cookie Header
func ServeToken(w http.ResponseWriter, r *http.Request, u *data.User) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"name":  u.Name,
		"email": u.Email,
		"exp":   time.Now().Unix(),
	})

	authToken, err := token.SignedString([]byte("secret"))
	if err != nil {
		log.Panic(err, os.Stdout)
	} else {
		cookie := http.Cookie{Name: "access_token", Value: authToken, MaxAge: 0}
		http.SetCookie(w, &cookie)
	}
}

Right now I have it being called in this Handler

// LoginHandler Handles requests for logging into Services
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		t, _ := template.ParseFiles("Templates/contentlayout.html", "Templates/publicnav.html", "Templates/login.html")
		t.Execute(w, "Login Page!")
	case "POST":
		r.ParseForm()
		user := data.User{}
		user.GetUser(r.PostFormValue("email"))
		if user.Password == r.PostFormValue("password") {
			WebUtils.ServeToken(w, r, &user)
			http.Redirect(w, r, "/dashboard/"+user.UUID, 301)
		} else {
			fmt.Fprintf(w, "Failed to Login user: %v", user.Name)
		}
	}
}

I’m hitting the redirect, but no Cookie. Also can you elaborate on the Panic? I believe it throws errors up the function chain, is this wrong?

log.Panic doesn’t take an argument where to write the panic, so you don’t want to pass os.Stdout, it won’t do what you think.

Any thoughts on why my Cookie isn’t being created?

For anyone following this thread who might experience the same problem that I had getting this to work. By default the path for the cookie that I was setting was the issuing path, so I set the path to root and now Cookie works just fine and I have a spiffy JWT auth system, though it needs some fleshing out!

Thanks for enlightening me about log.Panic as well.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.