英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论