为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 Golang 中读取 cookie(路由器:chi)

无法在 Golang 中读取 cookie(路由器:chi)

Go
白板的微信 2022-07-11 16:37:48
我正在为 todolist 应用程序开发 REST API(不是来自教程),并且我已经成功实现了身份验证,但是我的一个辅助函数似乎无法读取明显存在的 cookie,这里是函数:// jwt is imported from the https://github.com/dgrijalva/jwt-go packagefunc validateAccessToken(w http.ResponseWriter, r *http.Request) uuid.UUID {    jwtSecret, exists := os.LookupEnv("JWT_SECRET")    if !exists {        w.WriteHeader(500)        w.Write([]byte(`{"message":{"error":"Fatal internal error occurred"}}`))        panic(errors.New("JWT_SECRET environment variable not set"))    }    // Get access token and then validate it    at, err := r.Cookie("access_token")    if err == http.ErrNoCookie {        w.WriteHeader(401)        w.Write([]byte(`{"message":{"error":"access_token cookie not found"}}`)) // this error is always returned when i attempt to use the handler that uses this function        return uuid.Nil    }    t := at.Value    token, err := jwt.ParseWithClaims(t, &models.UserClaims{}, func(token *jwt.Token) (interface{}, error) {        return []byte(jwtSecret), nil    })    if claims, ok := token.Claims.(*models.UserClaims); ok && token.Valid {        return claims.ID    }    w.WriteHeader(401)    w.Write([]byte(`{"message":{"error":"access_token invalid"}}`))    return uuid.Nil}这是设置cookie的代码的相关部分:// Login handles the login routefunc Login(w http.ResponseWriter, r *http.Request) {    //...    // Construct cookies and then set them    rtCookie := http.Cookie{        Name:    "refresh_token",        Value:   *rt,        Expires: time.Now().Add(time.Nanosecond * time.Duration(sessionLifeNanos)),    }    atCookie := http.Cookie{        Name:    "access_token",        Value:   *at,        Expires: time.Now().Add(time.Minute * 15),    }    http.SetCookie(w, &rtCookie)    http.SetCookie(w, &atCookie)    w.Write([]byte(`{"message":"Logged in successfully :)"}`))}此外,每当我在邮递员中使用登录路由后进行检查时,所有 cookie 都会发送到 cookie jar 中(并且没有“access_token”cookie 未过期),并且具有正确的外观值。我很困惑为什么该validateAccessToken()函数找不到那里的cookie,这里也是serve()调用的函数main():我非常感谢任何帮助的尝试,我也为这个糟糕的问题道歉,我有点急于完成这个。
查看完整描述

2 回答

?
LEATH

TA贡献1936条经验 获得超7个赞

应用程序将 cookie 路径隐式设置为登录处理程序路径。通过将 cookie 路径显式设置为“/”来修复。


rtCookie := http.Cookie{

    Name:    "refresh_token",

    Path:    "/", // <--- add this line

    Value:   *rt,

    Expires: time.Now().Add(time.Nanosecond * time.Duration(sessionLifeNanos)),

}

atCookie := http.Cookie{

    Name:    "access_token",

    Path:    "/", // <--- add this line.

    Value:   *at,

    Expires: time.Now().Add(time.Minute * 15),

}


查看完整回答
反对 回复 2022-07-11
?
杨魅力

TA贡献1811条经验 获得超6个赞

我不确定,但我认为问题可能是由于 SameSite cookie 政策而出现的。如果您使用现代浏览器版本从在不同端口上运行的前端测试程序,则可能是浏览器不发送 cookie,因为它们没有SameSite 属性。


尝试将您的代码更改为:


rtCookie := http.Cookie{

        Name:    "refresh_token",

        Value:   *rt,

        SameSite: http.SameSiteNoneMode,

        Expires: time.Now().Add(time.Nanosecond * time.Duration(sessionLifeNanos)),


    }


查看完整回答
反对 回复 2022-07-11
  • 2 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号