This new middleware participates in authentication and acts as a filter
when the request doesn't include a valid CSRF token for a POST.
Any authentication middleware that you want to validate an antiforgery
token should go ahead of this middleware in the pipeline (Cookies,
IISIntegration). This also takes care of automatic auth (Windows) done by
weblistener.
Any authentication middleware that you want to ignore antiforgery should
go after this middleware in the pipeline.
To facilitate this, there are a few changes in the antiforgery API
surface. Namely we can now pass in a principal to validate tokens. You
can't pass in a principal to generate tokens - we expect you to be logged
in at that poing. Also, ValidateRequestAsync(...) now checks the HTTP verb
and won't validate GETs and such.
- #23 part 4
- depends on aspnet/HttpAbstractions@8c120a0
nits:
- correct name of a field in `AntiforgerySerializationContext`
- avoid allocations when returning an `AntiforgerySerializationContext` in (unlikely) case `Stream` is unused
- name literal `int` parameters
This code was popping up everywhere this method is called. Seems bad to
duplicate it. Really what the caller wants to know is 'is the request
valid or a potential CSRF exploit?'. This gets the API closer to that.
- #23 part 3
- `Get[AndStore]Tokens()` would deserialize cookie token from request even if `IsRequestValidAsync()` already had
- `GetAndStoreTokens()` serialized an old (never saved) cookie token once and a new one twice
- refactor serialization from `DefaultAntiforgeryTokenStore` to `DefaultAntiforgery`
- divide responsibilities and ease overall fix
- above refactoring took `IAntiforgeryContextAccessor` responsibilities along to `DefaultAntiforgery` as well
- store all tokens in `IAntiforgeryContextAccessor` to avoid repeated (de)serializations
- remove `AntiforgeryTokenSetInternal`
nits:
- bit more parameter renaming to `httpContext`
- remove argument checks in helper methods
- did _not_ do a sweep through the repo; just files in this PR
My earlier change to add TryValidateRequestAsync didn't go far enough,
because the store will still throw when the tokens aren't present. This
change is to make the store just return null tokens in these cases, and
move the exceptions to DefaultAntiforgery.
Some other misc cleanup
- docs for IAntiforgeryTokenGenerator
- Add HttpContext parameter where to all IAntiforgeryGenerator methods
- rename parameters on DefaultAntiforgery
This change adds support for retrieving an antiforgery CSRF token via a
configurable header in addition to the form field. This helps with doing
ajax requests in a 1st-party SPA when using cookie auth, and is similar to
functionality provided by a bunch of different frameworks.
In this change there's also a bunch of churn due to avoiding the term
'form' in favor of 'request' and 'session' in favor of 'cookie'. Where
code and error message now mention 'form' they specifically mean
form-encoded content.