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

Time:11-15

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.

CodePudding user response:

This is a good tutorial on Context: https://go.dev/blog/context. There are earlier SO discussions about contexts and middleware too, e.g. 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))
}
  • Related