Skip to content

[FEATURE] Make csrf and gorilla/schema compatible with each other without additional config #203

Description

@a-h

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

As per gorilla/schema#135 (comment) schema and csrf don't work well with each other.

I was creating a sample for templ - see https://github.com/a-h/templ/tree/main/examples/crud

By default, csrf creates a form post field of "gorilla.csrf.Token", which schema then complains about with: "schema: invalid path "gorilla.csrf.Token"

If you then rename the token, schema complains that the field can't be found on the struct.

So, to get these two libraries to work together, both require additional configuration.

On the csrf side, need to use csrf.FieldName to choose a name that doesn't have . characters in it (and set the csrf.TrustedOrigins, which isn't in the first part of the docs).

csrfKey := mustGenerateCSRFKey()
csrfMiddleware := csrf.Protect(csrfKey, csrf.TrustedOrigins([]string{"localhost:8080"}), csrf.FieldName("_csrf"))

On the schema side we have to ignore the unknown key with dec.IgnoreUnknownKeys, or add the _csrf field to the model.

var model Model

// Decode the form.
dec := schema.NewDecoder()
dec.IgnoreUnknownKeys(true)
err = dec.Decode(&model, r.PostForm)
if err != nil {
	h.Log.Warn("Failed to decode form", slog.Any("error", err))
	http.Error(w, err.Error(), http.StatusBadRequest)
	return
}

It seems to me that the two libraries should work together without any extra configuration, since it's a bit of a road bump for new users.

It seems that the best way might be to get schema to have a special case for gorilla.csrf.Token. I'll raise something similar on the schema side to get the conversation started.

Expected Behavior

The two libraries should work together without additional configuration.

Steps To Reproduce

See example in current behaviour.

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions