Testing POST with AntiForgeryToken

I have a service like this:

  1. GET /login
  2. POST /login

I am using ServiceStack.Razor to generate the view from GET /login, and it contains a call to
@Html.AntiForgeryToken() in the CSHTML. The HTML form posts back to POST /login

The HTML form of course ends up with something like this in it

<input name="__RequestVerificationToken" type="hidden" value="AfNLi-TnA2GVPwdwGNG1TR8AAAAA0" />

I am now integration testing my endpoints.

So to test the POST /logins endpoint, I will need to obtain a valid anti-forgery token (by scraping it out of a call to GET /login), and post back the cookie value from the previous request.

And then somehow pass the token into the request of the call to POST /login and set the cookie called “__RequestVerificationToken” with the cookie value from previous call.

Given that the request DTO of POST /login does not have a property called “__RequestVerificationToken” in it.
presumably, I would define a jsc.RequestFilter = req => {} and somehow set the form field “__RequestVerificationToken” data, and copy the cookie value in the request.

How would you actually do that, and would you do it in the RequestFilter?

The Anti Forgery Token implementation is originally from MVC where you’d call AntiForgery.Validate() to validate the token as seen in this answer:

Let’s forget about Anti-Forgery Tokens for the moment, that is just the context.

I am specifically asking, how do you inject an arbitrary name-value into a POST request, where that name-value does not exist in the request DTO? using a JsonServiceClient?

I need to include in my POST request the following name-value pair:

__RequestVerificationToken: AfNLi-TnA2GVPwdwGNG1TR8AAAAA0

from OP above.

If you just want to send arbitrary key/value pair data I’d add a Dictionary<string,string> property to your Request DTO which will let you send adhoc key/value pairs metadata with your Request DTO - we have a IMeta interface which formalizes this convention behind a Meta property.

The Content-Type of a POST request with JsonServiceClient is JSON so you can’t key/value Form Data Request Body but if you use the custom URL API, e.g:

TResponse Post<TResponse>(string relativeOrAbsoluteUrl, object requestDto)

You can add it as a queryString, e.g:

client.Post("/route?__RequestVerificationToken=AfNLi-TnA2GVPwdwGNG1TR8AAAAA0", requestDto);

Which will let you access it from IRequest.QueryString from request filters or your Service.