Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable .AspNetCore.Antiforgery Cookie

Is there any way to prevent the .AspNetCore.Antiforgery Cookie from being created in Asp.Net Core 2?

From my understanding services.addmvc internally calls AddAntiforgery and I cannot seem to find any way to prevent this?

The reason why this is important is because I cannot set any cookies before the user gives his consent and the .AspNetCore.Antiforgery cookie is set by default.

like image 798
Hansel Avatar asked May 18 '18 12:05

Hansel


2 Answers

OK, I found a solution. If you add this line to ConfigureServices in Startup.cs the cookie will never be created:

services.AddAntiforgery(options => { options.Cookie.Expiration = TimeSpan.Zero;});
like image 123
Hansel Avatar answered Sep 22 '22 13:09

Hansel


There are several options to disable automatic generation of antiforgery tokens and cookies from the docs:

Explicitly disable antiforgery tokens with the asp-antiforgery attribute (works well for me):

<form method="post" asp-antiforgery="false">
    ...
</form>

The form element is opted-out of Tag Helpers by using the Tag Helper ! opt-out symbol:

<!form method="post">
    ...
</!form>

Remove the FormTagHelper from the view. The FormTagHelper can be removed from a view by adding the following directive to the Razor view:

@removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers
like image 35
Ilya Chumakov Avatar answered Sep 26 '22 13:09

Ilya Chumakov