登录
首页 >  Golang >  Go问答

解决 golang 中“http:未找到命名 cookie”的问题

来源:stackoverflow

时间:2024-03-06 23:09:25 153浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《解决 golang 中“http:未找到命名 cookie”的问题》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在为几个我认识的人构建一个小型晚餐/计划管理应用程序(使用微服务)。目的是每个人都可以登录自己的帐户,然后可以使用不记名令牌 (jwt) 向其他服务进行身份验证。

此不记名令牌存储在 cookie 中。但是,设置后我找不到这个 cookie,我尝试再次检索它。

这最终会导致错误

http: named cookie not present

为什么请求的响应正文为空? 为什么我的 get 请求没有发送任何 cookie? 我该如何解决这个问题?

我在网上搜索了一下并尝试了以下方法

  • net/http cookie: 看起来最简单的实现,也是我在这里展示的实现。看来这个简单的例子应该可行。

  • cookiejar 实现: 我尝试使用 cookiejar 实现来设置和检索来自浏览器和邮递员的 cookie,但是它导致了相同的结果。我使用的 cookiejar 实现在 https://golang.org/pkg/net/http/cookiejar/?m=all#new

  • 中有描述
  • 设置为特定 url 和额外 get 请求: 我尝试将 cookie 放置在我的域内的不同特定 url 上。在某些时候,cookie 似乎只能从某个特定的绝对 url 检索,但事实并非如此。

  • httputil dumprequestout: 我发现net/http的实用程序包中有一个名为dumprequestout的函数,这个函数可能能够从请求中提取主体,但它也是空的。

  • 将 cookie“安全”标志设置为 false: 我发现一个建议,即安全标志使 cookie 无法读取。不幸的是,更改安全标志没有效果。

postman 清楚地表明 cookie 确实存在。我的浏览器(firefox)也显示cookies存在,但它们被赋予了一个相当抽象的名称。 postman 请求可以在 https://www.getpostman.com/collections/fccea5d5dc22e7107664 找到

如果我尝试使用 golang 中的“net/http”包检索 cookie,响应正文将显示为空。

在对用户/密码组合进行身份验证后,我设置会话令牌并直接重定向客户端。

// settokenandredirect sets an access token to the cookies
func settokenandredirect(w http.responsewriter, r *http.request, db *mgo.session, u *user.user, redirecturl string) *handler.apperror {
    // generate a unique id for the session token.
    tokenid := uuid.must(uuid.newv4()).string()
    //set the expiration time (found in config.config.go)
    expirationtime := time.now().add(config.expiretime)
    // set the cookie with the jwt
    http.setcookie(w, &http.cookie{
        name:     config.accesstokenname,
        value:    createtoken(u.userid, expirationtime, tokenid, r.header.get("user-agent")),
        expires:  expirationtime,
        httponly: true,
        secure:   false,
    })

    // redirects user to provided redirect url
    if redirecturl == "" {
        return handler.apperrorf(417, nil, "no redirect url has been provided")
    }
    http.redirect(w, r, redirecturl, 200)
    return nil
}

我尝试按如下方式验证传入请求和 jwt 令牌。

// all handlers will have this adapted servehttp function 
func (fn apphandler) servehttp(w http.responsewriter, r *http.request) {
    if err := authorize(w, r); err != nil {
        http.error(w, fmt.sprintf("not authorized: %v", err), http.statusunauthorized)
        return
    }
    if e := fn(w, r); e != nil { // e is *apperror, not os.error.
        log.printf("handler error: status code: %d, message: %s, underlying err: %#v",
            e.code, e.message, e.error)

        http.error(w, e.message, e.code)
    }
}
// claims defines what will be stored in a jwt access token
type claims struct {
    programversion string `json:"programversion"`
    useragent      string `json:"useragent"`
    jwt.standardclaims
}

// authorize checks if the jwt token is valid
func authorize(w http.responsewriter, r *http.request) error {
    c, err := r.cookie("access_token")
    if err != nil {
        if err == http.errnocookie {
            // the program returns this error
            return err
        }
        return err
    }

    tokenstring := c.value

    claim := &claims{}

    tkn, err := jwt.parsewithclaims(tokenstring, claim, func(tkn *jwt.token) (interface{}, error) {
        return config.jwtsigningsecret, nil
    })
    if !tkn.valid {
        return err
    }
    if err != nil {
        if err == jwt.errsignatureinvalid {
            return err
        }
        return err
    }

    // jwt token is valid
    return nil
}

设置cookie时,请求的结构如下

// pretty printed version
host: localhost:8080
content-type: application/json
user-agent: postmanruntime/7.11.0
cache-control: no-cache
accept-encoding: gzip, deflate
content-length: 68
connection: keep-alive
accept: */*
postman-token: 36268859-a342-4630-9fb4-c286f76d868b
cookie: access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoiug9zdg1hblj1bnrpbwuvny4xms4wiiwizxhwijoxntu2mja0mtg3lcjqdgkioijlzdlmmthhzi01ntawltq0ytetymrkzi02m2e4ywvhm2m0zdeilcjpyxqioje1ntyymdm1odcsimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.bssnjtz8wokwincdz_eowybctt9t6v-7pmlxfq7gvyo
// raw version
&{post /auth/users/login?redirect=/ http/1.1 1 1 map[cache-control:[no-cache] postman-token:[d33a093e-c7ab-4eba-8c1e-914e85a0d289] cookie:[access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoiug9zdg1hblj1bnrpbwuvny4xms4wiiwizxhwijoxntu2mja0ndu4lcjqdgkioiizotk1mmi1ns0yowqzltq4ngqtodhhnc1imdlhymi1oweynzgilcjpyxqioje1ntyymdm4ntgsimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.dfa7kbet3c2q1a9n1hxgmt0qbabhgavcdbpaypbdbi8] accept-encoding:[gzip, deflate] connection:[keep-alive] content-type:[application/json] user-agent:[postmanruntime/7.11.0] accept:[*/*] content-length:[68]] 0xc0001ba140  68 [] false localhost:8080 map[redirect:[/]] map[]  map[] [::1]:36584 /auth/users/login?redirect=/    0xc00016a2a0}

获取cookie时请求的结构如下

// pretty printed version
host: localhost:8080
cache-control: no-cache
postman-token: 20f7584f-b59d-46d8-b50f-7040d9d40062
accept-encoding: gzip, deflate
connection: keep-alive
user-agent: postmanruntime/7.11.0
accept: */*
// raw version
2019/04/25 12:22:56 &{get /path/provide http/1.1 1 1 map[user-agent:[postmanruntime/7.11.0] accept:[*/*] cache-control:[no-cache] postman-token:[b79a73a3-3e08-48a4-b350-6bde4ac38d23] accept-encoding:[gzip, deflate] connection:[keep-alive]] {}  0 [] false localhost:8080 map[] map[]  map[] [::1]:35884 /path/provide    0xc000138240}

设置炊具时的响应结构如下

response headers: map[location:[/] set-cookie:[access_token=eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9.eyjwcm9ncmftvmvyc2lvbii6ijeumc4wiiwidxnlckfnzw50ijoir28tahr0cc1jbgllbnqvms4xiiwizxhwijoxntu2mji4odiylcjqdgkioijly2q2nwrkzi1jzjviltq4n2ytytnkyy00nmm3n2iymmuzmwuilcjpyxqioje1ntyymjgymjisimlzcyi6imdrlmp3dc5wcm9mawxlu2vydmljzs5hin0.0sovezqs2gczjwsmtvsd_u0qmv2l7m4hkf1kum08-bq; expires=thu, 25 apr 2019 21:47:02 gmt; httponly] date:[thu, 25 apr 2019 21:37:02 gmt] content-length:[0]]

我预计 authorize 函数将返回 nil。另外,如果我添加以下代码,我希望存在一些 cookie。

for _, cookie := range r.Cookies() {
    fmt.Fprint(w, cookie.Name)
}

但是,authorize 函数在标题中返回错误,并且 printf 没有打印出任何 cookie。


解决方案


记住设置cookie的路径:

c := &http.Cookie{Name: name, Value: encode(value), Path: "/"}
    http.SetCookie(w, c)

如果不这样做,path 将是当前请求的路径,因此 cookie 只能从这个确切的路径中获得。

理论要掌握,实操不能落!以上关于《解决 golang 中“http:未找到命名 cookie”的问题》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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