Repository navigation
Open
Description
Hi there, I'm using nethttp-middleware for my project and I wanted to create an authentication middleware using middleware.OapiRequestValidatorWithOptions.
I was trying to find ways to validate JWT token, extract subject value and then set it into the request context - all in the auth middleware.
My authentication middleware looks roughly like this:
func NewAuthenticator(tokenSecret string) openapi3filter.AuthenticationFunc {
return func(ctx context.Context, input *openapi3filter.AuthenticationInput) error {
request := input.RequestValidationInput.Request
claims, err := validateTokenInRequest(request, tokenSecret)
if err != nil {
return err
}
sub, err := claims.GetSubject()
if err != nil {
slog.Error("could not get sub", "err", err)
}
slog.Info("claims", "sub", sub)
claimsContext := api.SetUserId(request.Context(), sub)
input.RequestValidationInput.Request = request.WithContext(claimsContext)
return nil
}
}But my http handler that is called later does not see the value in request context.
It seems like the problem lays here:
nethttp-middleware/oapi_validate.go
Lines 179 to 194 in 40670ca
| requestValidationInput := &openapi3filter.RequestValidationInput{ | |
| Request: r, | |
| PathParams: pathParams, | |
| Route: route, | |
| } | |
| if options != nil { | |
| requestValidationInput.Options = &options.Options | |
| } | |
| err = openapi3filter.ValidateRequest(r.Context(), requestValidationInput) | |
| if err == nil { | |
| // it's a valid request, so serve it | |
| next.ServeHTTP(w, r) | |
| return | |
| } |
Even though I assigned new request to
RequestValidationInput, the next handler is called with the original request that is stored in the r variable.An obvious workaround is to change:
next.ServeHTTP(w, r)to
next.ServeHTTP(w, requestValidationInput.Request)Is that a bug or is there another way of setting values in request context that I'm not aware of?
Any help would be appreciated, thanks!
Reacted by esprimo, Subroto, MaxHf, Ori, Christophe Lecroq and Arne Leitert
Reacted by Dawid Gurgul and Jamie Tanna
Metadata
Metadata
Assignees
Labels
No labels
Activity
Dejvinczi commentedon Oct 1, 2025
+1
esprimo commentedon Oct 5, 2025
I'm in a similar boat.
Looking at the authenticated-api example, updating the context is left as a todo:
Note that this is not the example for Echo but for stdhttp, that part of the comment is just a copy from the Echo example.
phoenisx commentedon Oct 18, 2025
A workaround for now (and I feel it's better than modifying http.Request.Context()) could be to create ur own context in ur Routes struct, or whatever struct u are using to manage ur oapi routes/controllers, and update/use that context to access oapi controller data.