jjzjj

http - 如何在 golang 中修复 'http: named cookie not present'?

coder 2023-06-26 原文

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

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

最终导致错误

http: named cookie not present

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


我在网上搜索了一下并尝试了以下操作

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

  • Cookiejar 实现: 我尝试使用 cookiejar 实现来设置和检索来自浏览器和 postman 的 cookie,但结果相同。 https://golang.org/pkg/net/http/cookiejar/?m=all#New 中描述了我使用的 cookiejar 实现

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

  • httputil DumpRequestOut: 我发现net/http的工具包有一个函数叫做DumpRequestOut,这个函数可能已经可以从请求中提取body,但是这个也是空的。

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


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

如果我尝试使用来自 golang 的“net/http”包检索 cookie,响应主体会变成空的。

我设置 session token 并在我验证用户/密码组合后直接重定向客户端。

// 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 token 。

// 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 <nil> 68 [] false localhost:8080 map[redirect:[/]] map[] <nil> map[] [::1]:36584 /auth/users/login?redirect=/ <nil> <nil> <nil> 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]] {} <nil> 0 [] false localhost:8080 map[] map[] <nil> map[] [::1]:35884 /path/provide <nil> <nil> <nil> 0xc000138240}

设置cooke

时,响应结构如下
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 将只能从这个确切的路径获得。

关于http - 如何在 golang 中修复 'http: named cookie not present'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55850042/

有关http - 如何在 golang 中修复 'http: named cookie not present'?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  8. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby - 如何模拟 Net::HTTP::Post? - 2

    是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou

随机推荐