Skip to content

middleware.OapiRequestValidatorWithOptions does not keep request context set in authentication middleware #60

@szykol

Description

@szykol

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:

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions