lonix
lonix

Reputation: 21011

Rename ASP.NET Core's antiforgery cookie and maintain random part

ASP.NET Core's anti-forgery cookie name is .AspNetCore.Antiforgery.XXX where the last bit is random.

The cookie can be renamed like so:

builder.Services.AddAntiforgery(x => x.Cookie.Name = "Foo");

But that will produce a cookie named Foo rather than Foo.XXX.

The options object has a field AntiforgeryOptions.DefaultCookiePrefix. Unfortunately it's readonly.

What is the purpose of the random substring (and is it really random or some sort of key?), and how can I rename the cookie so it still has that substring?

Upvotes: 1

Views: 435

Answers (1)

Cristian Olaru
Cristian Olaru

Reputation: 485

solution for .NET 8

define the following class:

internal class UnsafeAccessorClassAntiforgeryOptions
{
    [UnsafeAccessor(UnsafeAccessorKind.StaticField, Name = "DefaultCookiePrefix")]
    public static extern ref string GetUnsafeStaticFieldDefaultCookiePrefix(AntiforgeryOptions obj);
}

then in Program.cs as the first line:

UnsafeAccessorClassAntiforgeryOptions.GetUnsafeStaticFieldDefaultCookiePrefix(new()) = ".AntiForgery.";

more info about UnsafeAccessorAttribute at:

https://medium.com/@malarsharmila/introduction-to-the-unsafeaccessorattribute-class-in-net-8-0-d3a55ec15762

Upvotes: 0

Related Questions