Golang REST API – 从已验证和解码的令牌中传递信息

huangapple go评论87阅读模式
英文:

Golang REST API - passing information from a verified and decoded token

问题

我已经设置了中间件来验证和提取JWT令牌中的声明(使用https://github.com/golang-jwt/jwt)。

我的问题是,我想以某种方式将这些信息传递给路由处理函数,以便它可以检查存储在令牌中的权限。

我在这方面找不到好的资源,但我看到有两个建议,一个是使用REDIS在验证后存储令牌信息,另一个是使用http.Request上下文。

我宁愿不使用REDIS,所以我认为只剩下上下文了?尽管我在整个上下文和这种用例的上下文方面都很困惑,找不到合适的资源。

另一种选择是让中间件验证令牌,然后在处理程序函数内部提取JWT声明而无需再次验证令牌。

非常感谢任何帮助/链接/建议...我知道在Go中有很多种方法,但我宁愿遵循最佳实践。

英文:

I have set up middleware to verify and extract the claims from the JWT token (using https://github.com/golang-jwt/jwt).

My problem now is I want to pass that information on somehow to the route hander func so that it can check the permissions that was stored inside the token.

I am struggle to find good resources on this, but I have see two suggestions, one using REDIS to store the token information once it has been verified, and the other is to use the http.Request context.

I would rather not use REDIS, so I assume that only really leaves me with Context? Although I am struggling to find decent resources on context as a whole, and context for this type of use case.

Another alternative would be to just have the middleware verify the token, then within the handler funcs' themselves, extract the JWT claims without verifying the token again?

Any help/links/advice would be much appreciated... I know there are many ways to skin a cat in Go, but I would rather follow best practice.

答案1

得分: 2

这是关于Context的一个很好的教程:https://go.dev/blog/context。
之前也有一些关于上下文和中间件的讨论,例如:https://stackoverflow.com/questions/39946583/how-to-pass-context-in-golang-request-to-middleware

你可以使用context.WithValue将任意的键值对映射添加到上下文中,然后使用请求的WithValue方法:

可以简单地这样写:

func middleware(rw http.ResponseWriter, req *http.Request, next http.Handler) {
    ctx := context.WithValue(req.Context(), "key", "value")
    next.ServeHTTP(rw, req.WithContext(ctx))
}
英文:

This is a good tutorial on Context: https://go.dev/blog/context.
There are earlier SO discussions about contexts and middleware too, e.g. https://stackoverflow.com/questions/39946583/how-to-pass-context-in-golang-request-to-middleware

You can use context.WithValue to add arbitrary key->value mappings onto a context, and then the request's WithValue method:

It can be as simple as:

func middleware(rw http.ResponseWriter, req *http.Request, next http.Handler) {
	ctx := context.WithValue(req.Context(), "key", "value")
	next.ServeHTTP(rw, req.WithContext(ctx))
}

huangapple
  • 本文由 发表于 2021年11月12日 06:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69935887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定