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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With