ASP.NET Core 9: File Upload using APIs with IFormFile and Anti-Forgery Token

In this micro article, we will be discussing the important change in File Upload feature in ASP.NET Core 9 for IFormFile. I have already written an article for File upload using Minimal APIs on this link. This article is an enhancement in that article. In ASP.NET Core 9, a strict anti-forgery validation for file uploads for IFormFile. While using Minimal APIs endpoints, for file upload using IFormFile or IFormFileCollection, we need to pass an Anti-Forgery token into the HTTP request header. This token will be validated before completing the file upload operations.  

The Minimal API must use the Anti Forgery Token Service as well as the Anti Forgery Token Middleware else the exception will be thrown. The reason behind the change is for the security precaution for the API that consumes data posted form the form. Although we can disable the Anti Forgery token it is not recommended, please avoid it for the production. 

In the Minimal API project created with ASP.NET Core 9, in Program.cs we can add the endpoint for creating Minimal API as shown in code in Listing 1:


app.MapGet("/antiforgery-token", (IAntiforgery antiforgery, HttpContext context) =>
{
    var tokens = antiforgery.GetAndStoreTokens(context);
    return Results.Ok(new { token = tokens.RequestToken });
});

Listing 1: The Minimal API Endpoint for receiving Minimal Token

The code on Listing 1 shows the endpoint that has the Input parameter as IAntiForgery. This interface provides an access to the anti-forgery system that helps to protect against CSRF attacks. The method GetAndStoreTokens(HttpContext) is used to generate an anti-forgery token set and store the cookie token in the response.  There are several other methods defined in this interface. 

Let's add a new Minimal API endpoint to upload the file as shown in Listing 2. 


app.MapPost("/upload", async (IFormFile receivedFile) =>
{
    // Read the folder where the file is to be saved
    var folder = Path.Combine(Directory.GetCurrentDirectory(), "files");
    // REad the Uploaded File Name
    var postedFileName = ContentDispositionHeaderValue
        .Parse(receivedFile.ContentDisposition)
        .FileName.Trim('"');

    // set the file path as FolderName/FileName
    var finalPath = Path.Combine(folder, postedFileName);
    using var fs = File.OpenWrite(finalPath);
        
    await receivedFile.CopyToAsync(fs);
        
});

Listing 2: Endpoint to upload file

Modify the Program.cs by adding Anti-Forgery service and middleware as shown in Listing 3.

.......

builder.Services.AddAntiforgery();

........................
......................
..........................
app.UseAntiforgery(); 

YOUR ENDPOINTS HERE


Listing 3: The Anti-Forgery Service and Middleware

 

Run the application and test it in the Advanced REST Client or in Postman. As shown in the Figure 1, get the Anti-Forgery token:



Figure 1: Get Anti-Forgery Token

 As shown in the Figure 2, send the Anti-Forgery Token in the HTTP Request Header.



Figure 2: Send the Token in the Header of the POST request

This token will be validated by issuer.  Complete the POST request for file upload as shown in Figure 3.



Figure 3: File Upload

Make sure that the Name parameter matches with the name of the IFormFile file parameter passed to the upload endpoint.  In our case it is receivedFile.    


Once the Anti-Forgery token is added the file can be uploaded successfully.

   


Popular posts from this blog

Uploading Excel File to ASP.NET Core 6 application to save data from Excel to SQL Server Database

ASP.NET Core 6: Downloading Files from the Server

ASP.NET Core 6: Using Entity Framework Core with Oracle Database with Code-First Approach