Skip to content

How to use headers, not cookies #72

@assistcontrol

Description

@assistcontrol

With a JSON API, it makes much more sense to use HTTP headers, not cookies, to transmit CSRF tokens (please correct me if I am wrong!).

The README shows how to manually validate tokens, but not how to manually create them. This is a request to help me understand how to accomplish this, and then add it to the README :)

The behaviour I'm looking for is to get a valid token string, without creating cookies as a side effect. Essentially, I'm trying to get nosurf to operate in header mode instead of cookie mode.

Attempt 1:

func AddCSRFHeader(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("X-CSRF-Token", nosurf.Token(r))
    next.ServeHTTP(w, r)
  })
}

This generates an empty string every time.

Attempt 2:

func AddCSRFHeader(next http.Handler) http.Handler {
  return nosurf.New(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {  //nosurf.New() added here
    w.Header().Set("X-CSRF-Token", nosurf.Token(r))
    next.ServeHTTP(w, r)
  }))
}

This generates a token, but also applies a cookie (which I'm trying to avoid).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions