I added global authorization to a Blazor server application using this code in Program.cs:
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
It works well. This also gives me the option disable authorization on a specific page by adding @attribute [AllowAnonymous]
to it. I added the attribute to the sign-in page which looks like so:
However, without any errors in the console, the page's styling always breaks if I visit it incognito:
But the moment I sign in, every page's styling works again.
This behavior is leading me to believe that global authorization prevents the app from retrieving styling files, but I don't know how to fix that.
One way of fixing it that worked was to remove global authorization and authorize only the pages that need it. However, I like the global approach better because then during development I don't need to worry about forgetting to authorize a page.
How can I keep global authorization and fix this issue with page styling?
You can ensure that the static file middleware is added before the authorization, like:
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
Then, You can try to use middleware to allow anonymous users to access static resources. For example:
app.Use(async (context, next) =>
{
// Allow anonymous access to specific static resources (e.g., CSS and JS)
if (context.Request.Path.StartsWithSegments("/css") ||
context.Request.Path.StartsWithSegments("/js") ||
context.Request.Path.StartsWithSegments("/_content"))
{
// Set an anonymous user identity
context.User = new ClaimsPrincipal(new ClaimsIdentity();
}
await next();
});