登录
首页 >  Golang >  Go问答

最佳实践:在 httpOnly cookie 中安全存储 JWT

来源:stackoverflow

时间:2024-02-29 09:39:30 355浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《最佳实践:在 httpOnly cookie 中安全存储 JWT》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我找到了 securecookie 模块,我想用它来将 jwt 令牌(访问和刷新)存储在 httponly cookie 中,以便在 rest api 中使用。

以下代码引用自上述官方 github 页面 - 我不确定“值字符串映射”的含义:

func SetCookieHandler(w http.ResponseWriter, r *http.Request) {
    value := map[string]string{
        "foo": "bar",
    }
    if encoded, err := s.Encode("cookie-name", value); err == nil {
        cookie := &http.Cookie{
            Name:  "cookie-name",
            Value: encoded,
            Path:  "/",
            Secure: true,
            HttpOnly: true,
        }
        http.SetCookie(w, cookie)
    }
}

换句话说:我应该在哪里保存我的代币?它们会转到“值”字符串映射还是应该是在编码函数之后创建的“cookie”对象中的属性?

顺便提一下:我也在使用 gin 框架,但这不会改变这里的任何内容。


解决方案


securecookie 唯一做的就是将您的令牌值转换为编码字符串。 然后您可以在向客户端设置 cookie 时将其视为令牌的新值。

encode 可以使用任何数据类型,并不总是必须是 map[string]string,您可以直接将 jwt 令牌传递给它。

encoded, err := s.encode("jwt-token", "value.of.jwt.token.here")

之后,不能比示例中的键值格式更简单了:

cookie := &http.Cookie{
        Name:     "jwt-token", // <- should be any unique key you want
        Value:    encoded, // <- the token after encoded by SecureCookie
        Path:     "/",
        Secure:   true,
        HttpOnly: true,
    }
    http.SetCookie(w, cookie)

当您想再次验证令牌时,请记住使用正确的密钥 jwt-token 解码 encoded cookie。

今天关于《最佳实践:在 httpOnly cookie 中安全存储 JWT》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>