我正在为几个我认识的人构建一个小型的晚餐/计划管理应用程序(使用微服务)。目的是使每个人都可以登录自己的帐户,然后可以使用承载令牌(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上。在某些时候,似乎只能从某个特定的绝对URL中检索cookie,事实并非如此。
httputil DumpRequestOut:我发现net / http的实用程序包具有一个称为DumpRequestOut的函数,该函数可能已经能够从请求中提取主体,但是它也是空的。
将cookie的“安全”标志设置为false:我发现一个建议,即安全标志使cookie无法读取。不幸的是,更改安全标志无效。
邮递员清楚地表明cookie确实存在。我的浏览器(firefox)也显示cookie存在,但是给了它们一个相当抽象的名称。邮递员的请求可以在https://www.getpostman.com/collections/fccea5d5dc22e7107664找到
如果我尝试使用golang中的“ net / http”包来检索Cookie,则响应主体将显示为空。
在验证用户/密码组合后,我设置了会话令牌并直接重定向客户端。
http: named cookie not present
我尝试如下验证传入的请求和JWT令牌。
// 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
}
// 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)
}
}
设置Cookie时,请求的结构如下
// 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
}
// 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
获取Cookie时,请求的结构如下
// 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}
// 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}
我希望Authorize函数将返回nil。另外,如果我添加以下代码,我希望其中存在一些cookie。
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函数将在标题中返回错误,并且printf不会打印出任何cookie。