dongweihuai5601 2019-07-23 21:24
浏览 229

如何通过golang中的重定向发送cookie?

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 already try: - 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 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)

Does any of you guys have an idea in order to pass the cookie from the authentication endpoint to the home page ?

  • 写回答

1条回答 默认 最新

  • drpjdfj618393 2019-07-24 00:14
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等