nosurf icon indicating copy to clipboard operation
nosurf copied to clipboard

Is it possible to get the Token from a request but only having access to its context?

Open antonisgkamitsios opened this issue 1 year ago • 1 comments

I am facing an issue when although i am able to get the token from the request via the token := nosurf.Token(r) sometimes i want to have access to it but only the request's context is available to me (I am referring to the golang's Templ which gives the ctx as a global) So My solution is to add a middleware that will get the token from the request via the nosurf.Token(r) and then pass it down my own in a context and then later access it only via a context with something like

func GetCSRF(ctx context.Context) string {
	if token, ok := ctx.Value(CSRFContextKey).(string); ok {
		return token
	}

	return ""
}

And i was wandering, seing the code of the nosurf.Token function, maybe perhaps we could add another function for example TokenCtx which we would accept a context instead of a request? Or perhaps my approach is problematic and i have to rethink about my solution

antonisgkamitsios avatar Mar 25 '25 13:03 antonisgkamitsios

This is a good idea. Token() and Reason() have the signatures that they do, because nosurf predates introduction of context.Context (the pre Go 1.7 implementation using a global map is still in the repo).

I see no issue with introducing TokenFromContext, or TokenContext or TokenCtx. Not sure about the correct naming convention off the top of my head!

justinas avatar Mar 28 '25 12:03 justinas