How to produce Antiforgery Token in blazor Server and blazor WebAssembly in .Net 8.0 in an Client Server Architecture

121 views Asked by At

As our application is crossed from the Coverity Scan , there was an high impact in the application says that the CSRF attack is found. In order to prevent CSRF attacks I tired to implement the Antiforgery token concept in our blazor webassembly and blazor Server as an client - Server architecture. Where I couldn't able to find the hidden input field from the Component and there is no value is generated.

In client I have added the Component inside the form tag

<form method = "post"@onsubmit="UpdateInputs">
     <AntiforgeryToken/>
         <button type="submit" class="btn btn-sm btn-primary" data-bs-dismiss="modal">Ok</button>
         <button type="button" class="btn btn-sm btn-primary" data-bs-dismiss="modal" @onclick="clear">Cancel</button>    
 </form>

but there is no input hidden field is appeared while the form is submitted.

In Server I added the [ValidateAntiForgeryToken] in the controller and in Program.cs file I added the

builder.Services.AddAntiforgery(); app.UseAntiforgery();

What Am I missing or What i need to do with above code, to produce the antiforgery token.

1

There are 1 answers

14
Tiny Wang On

First of all, according to your description, the blazor server app plays the role of a backend which looks like a web API, and you also confirmed that it's client-server architecture, so that it is not necessary to implement Anti-Forgery Token protection against CSRF Attacks. As the web api is stateless, it doesn't setup a user session with the client. Here's the description about Prevent Cross-site Request Forgery from microsoft, you shall find it related to browser-server session. This usually happened in MVC app or razor page webapp, for blazor wsam(SPA) + backend server API, we should handle it following this section and this document. I recommend using access token mechanism to secure the backend server.

By the way, in MVC project, antiforgery mechanism is used by default, when we submit form, the anti-forgery key will be submitted by the hidden input just like what you said, but in blazor wsam, we still need to create a submit method to send the http request, which should use code below at least, instead of adding <AntiforgeryToken/> component.

private async Task OnSubmit()
{
    var antiforgery = Antiforgery.GetAntiforgeryToken();
    var request = new HttpRequestMessage(HttpMethod.Post, "action");
    request.Headers.Add("RequestVerificationToken", antiforgery.RequestToken);
    var response = await client.SendAsync(request);
    ...
}