tteixeira
tteixeira

Reputation: 351

How to send cookie through redirection in golang?

I'm working on an api, and after I authenticate an user, I would like to redirect him to the main page, passing through a cookie, which contain a jwt token.

I'm using the http.Redirect function and I have already tried the following:

That's the code I use with the http.SetCookie function, which is the one that work out the best:

strToken := CreateToken(user)
urlAuthRedirect := "https://komfy.now.sh"

cookie := http.Cookie{
    Name: "jwt-token",
    Value: strToken, 
}

http.SetCookie(resp, &cookie) 
http.Redirect(
    resp, // ResponseWriter
    req, // Request
    urlAuthRedirect, 
    http.StatusSeeOther)

How do I pass the cookie from the authentication endpoint to the home page?

Upvotes: 8

Views: 6567

Answers (1)

Thundercat
Thundercat

Reputation: 120941

If a set cookie header does not specify a path, then the browser defaults the path to the path of the request. To make a cookie available across an entire site, explicitly set the path to "/".

cookie := http.Cookie{
    Name: "jwt-token",
    Value: strToken, 
    Path: "/",
}

Cookies cannot be set cross domain. If the auth handler in the question is not served from the domain komfy.now.sh, then the cookie cannot be set directly. The workaround is to send the token through a query parameter to an endpoint on the target domain. The handler for that endpoint sets the cookie and possibly redirects to the final URL.

Upvotes: 10

Related Questions