Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
如何在Golang中处理cookie和token_创想鸟

如何在Golang中处理cookie和token

答案:在Golang中通过net/http设置Cookie使用http.SetCookie,读取用r.Cookie,Token常用JWT实现,生成后可通过Cookie或Header传输,结合HttpOnly、Secure、SameSite可提升安全性,验证时解析Authorization头或Cookie中的Token并校验有效性。

如何在golang中处理cookie和token

在Golang中处理Cookie和Token是Web开发中的常见需求,尤其在实现用户认证、会话管理时尤为重要。合理使用Cookie和Token可以提升安全性与用户体验。下面介绍如何在标准库 net/http 的基础上操作Cookie和Token。

设置和读取Cookie

Cookie通常用于保存客户端的小量数据,比如会话标识(session ID)或用户偏好。

设置Cookie: 使用 http.SetCookie 函数向响应中写入Cookie。

http.SetCookie(w, &http.Cookie{    Name:     "session_id",    Value:    "abc123xyz",    Path:     "/",    HttpOnly: true,    MaxAge:   3600,})

上述代码设置了名为 session_id 的Cookie,值为 abc123xyz,有效期1小时,仅限HTTP访问,防止XSS攻击。

立即学习“go语言免费学习笔记(深入)”;

读取Cookie: 使用 r.Cookies() 或 r.Cookie(name) 获取请求中的Cookie。

cookie, err := r.Cookie("session_id")if err != nil {    http.Error(w, "未登录", http.StatusUnauthorized)    return}fmt.Println("Session ID:", cookie.Value)

使用Token进行身份验证

Token(如JWT)常用于无状态认证。服务器签发Token,客户端在后续请求中携带它,通常放在 Authorization 头中。

生成JWT Token示例:

import "github.com/golang-jwt/jwt/v5"

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{"userid": 123,"exp": time.Now().Add(time.Hour * 24).Unix(),})tokenString, := token.SignedString([]byte("your-secret-key"))

将生成的 tokenString 返回给客户端,客户端在请求头中携带:

Authorization: Bearer 

解析和验证Token:

header := r.Header.Get("Authorization")if header == "" {    http.Error(w, "缺少Token", http.StatusUnauthorized)    return}

parts := strings.Split(header, " ")if len(parts) != 2 || parts[0] != "Bearer" {http.Error(w, "无效的Token格式", http.StatusForbidden)return}

parsedToken, err := jwt.Parse(parts[1], func(token *jwt.Token) (interface{}, error) {return []byte("your-secret-key"), nil})if err != nil || !parsedToken.Valid {http.Error(w, "无效或过期的Token", http.StatusUnauthorized)return}

结合Cookie存储Token

为了兼顾安全性和便利性,可以将Token通过Cookie发送给客户端,并设置安全属性。

http.SetCookie(w, &http.Cookie{    Name:     "auth_token",    Value:    tokenString,    Path:     "/",    HttpOnly: true,    Secure:   true, // 启用HTTPS    SameSite: http.SameSiteStrictMode,    MaxAge:   86400,})

这样可防止JavaScript访问Token(防XSS),同时限制跨站请求(CSRF防护可通过SameSite实现)。

从Cookie中读取Token的方式与普通Cookie一致:

cookie, err := r.Cookie("auth_token")if err != nil {    http.Error(w, "请登录", http.StatusUnauthorized)    return}tokenString := cookie.Value// 然后解析JWT

基本上就这些。关键在于理解Cookie的作用域、安全标志以及Token的签发与验证流程。不复杂但容易忽略细节。

以上就是如何在Golang中处理cookie和token的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1417574.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Golang如何判断错误类型
上一篇 2025年12月16日 11:30:15
Golang如何实现微服务负载均衡
下一篇 2025年12月16日 11:30:24

相关推荐

发表回复

登录后才能评论
关注微信