Uploader Anti-Forgery Token

0 Answers 45 Views
Upload
Lenny
Top achievements
Rank 1
Lenny asked on 23 Sep 2024, 06:13 PM
Is there a way to disable sending the token in the form? We would prefer to send it in the header.
Anton Mironov
Telerik team
commented on 26 Sep 2024, 09:09 AM

Hi Lenny,

Thank you for the details provided.

In order to achieve the described behavior, I would recommend to configure the anti-forgery settings as follows:

In your Startup.cs or Program.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddAntiforgery(options =>
    {
        options.HeaderName = "X-CSRF-TOKEN";  
    });
}
Modify the client-side code for the Upload Event:
var token = $('input[name="__RequestVerificationToken"]').val();  
e.XMLHttpRequest.setRequestHeader("X-CSRF-TOKEN", token); 

Ensure the anti-forgery token is available in the View:
@Html.AntiForgeryToken()
Receive the token in the Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upload(IFormFile file)
{

}
I hope this information helps.

Kind Regards,

Anton Mironov

Lenny
Top achievements
Rank 1
commented on 26 Sep 2024, 03:32 PM

Thanks. I figured it out.  I added this bit of script to the Upload client side event handler.

 

        var xhr = e.XMLHttpRequest;
        if(xhr) {
            xhr.addEventListener("readystatechange", function (e) {
                if (xhr.readyState == 1 ) {
                    xhr.setRequestHeader('RequestVerificationToken', getAntiForgeryToken());
                }
            });
        }
Anton Mironov
Telerik team
commented on 01 Oct 2024, 11:31 AM

Hi Lenny,

Thank you for sharing the code with the community.

Best Regards,
Anton Mironov

No answers yet. Maybe you can help?

Tags
Upload
Asked by
Lenny
Top achievements
Rank 1
Share this question
or