Guidance on Appropriate Value for First Parameter in AntiForgery.GetTokens

We are currently using the following code in our application:

ServiceStack.Html.AntiXsrf.AntiForgery.GetTokens(null, out newCookieToken, out formToken);

In this implementation, we are passing null as the first parameter to the GetTokens method.
Could you please tell us what is the best practice?

This is an old implementation of ASP .NET Framework MVC AntiForgery class:

Where:

The anti-forgery token - if any - that already existed for this request. May be null. The anti-forgery system will try to reuse this cookie value when generating a matching form token.

Passing null is valid, but the best practice is to pass the existing cookie token value if one already exists for the current request/user session.

  • When you pass null, the system will always generate a new cookie token, which means you must always update the response cookie.

  • When you pass the existing cookie token, the system can reuse it if still valid, and newCookieToken will be null on output - so no cookie update is needed, reducing unnecessary churn.

It’s likely over a decade since I’ve used this, but the idea is you only need to set a new cookie token if one hasn’t existed. Here’s a good old video from Troy Hunt explaining how it works and that it’s recommended to use an existing cookie token if it exists.

If you set null you’re basically telling it to create and set a new cookie token each time:

// Read the existing cookie token (if any) from the request
string existingCookieToken = Request.Cookies["__RequestVerificationToken"]?.Value;

string newCookieToken, formToken;
AntiForgery.GetTokens(existingCookieToken, out newCookieToken, out formToken);

// Only update the cookie if a new one was issued
if (newCookieToken != null)
{
    Response.Cookies["__RequestVerificationToken"].Value = newCookieToken;
}