Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send cookie through redirection in golang?

Tags:

http

cookies

go

api

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:

  • Set the cookie to the ResponseWriter and send it through the redirect function but all it does it's setting a cookie on the authentication page but it doesn't pass it through the redirection, so the home page doesn't receive it.

  • Add the cookie to the request I first receive with the handler function and resent it through the redirect function. This doesn't work at all.

  • Create a new request and send it through the redirect function once again. This also doesn't work.

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?

like image 996
Thomas Teixeira Avatar asked Mar 03 '23 16:03

Thomas Teixeira


1 Answers

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.

like image 183
Bayta Darell Avatar answered Mar 08 '23 04:03

Bayta Darell