I am converting a Blazor ver 6/7 Server to ver 8 InteractiveServer.
In ver 6/7 I set up anti-forgery with the following in _Host.cshtml
@inject IAntiforgery Xsrf
// ...
<body>
@{
var initialTokenState = new InitialApplicationState
{
XsrfToken = Xsrf.GetAndStoreTokens(HttpContext).RequestToken,
Cookie = HttpContext.Request.Cookies[".AspNetCore.Cookies"],
RemoteIp = HttpContext.GetRemoteIpAddress(Logger)
};
}
I moved the content of _Host.cshtml to App.razor and in App.razor, it has no HttpContext
property. This documentation discusses submitting a form, but nothing about setting it up for rendering a page. When I try to run and render a page (no form on it), I get:
InvalidOperationException: Endpoint /sitemap (/sitemap) contains anti-forgery metadata, but a middleware was not found that supports anti-forgery.
Configure your application startup by adding app.UseAntiforgery() in the application startup code. If there are calls to app.UseRouting() and app.UseEndpoints(...), the call to app.UseAntiforgery() must go between them. Calls to app.UseAntiforgery() must be placed after calls to app.UseAuthentication() and app.UseAuthorization().
Clearly there are different steps I should be taking for anti-forgery in version 8. Where is this documented? And in my case - no endpoints. My app is going from rendermode ver 6/7 server to ver 8 InteractiveServer. (And a Google search for useantiforgery
just leads to others asking about all this.)
Warning - the below works. However, I do not know if it is correct and I do not know if this stops forgery attacks. I'm using what another person found works and they did not seem sure if this is correct. But it works and no one else has answered, so I figure better than no answer. I will update if I get an authoritative answer.
I replaced:
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
if (builder.Environment.IsProduction())
app.MapHealthChecks("health").AllowAnonymous();
with:
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.MapRazorPages();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
if (builder.Environment.IsProduction())
app.MapHealthChecks("health").AllowAnonymous();
If this is all that's required - great move on the part of the Blazor team - a lot easier than what was required before.