I ran into some strange behaviour with the authorization in Blazor with .NET 8. The sample is a slightly modified version of the Blazor Web App template with its default settings (no authorization).
I did manually add authorization because our requirements are not met with the default authorization template of Blazor. I explain further down below what I did to add authorization.
With authorization enabled and the home page marked with the Authorize attribute, I expect the website to show me the text "Login" when I start it because I am not authorized:
Routes.razor
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<span>Login</span>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
</Router>
Home.razor
@page "/"
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@...
However, the expected behaviour does not happen. Instead I get a 401 error on the very first web request and nothing is shown.
To make things even more strange, when I completely remove the Routes component from the App.razor file (which appears to be some sort of an entry point for the entire website) I still get the same 401 error even though there is no routing at all to the Home component:
App.razor
<!DOCTYPE html>
<html lang="en">
<!-- ... -->
<body>
Hello App
@* <Routes @rendermode="@InteractiveAuto" /> *@
<script src="_framework/blazor.web.js"></script>
</body>
</html>
If on the other hand I remove the Authorize attribute from the Home component (which isn't even referenced), the website suddenly works and shows "Hello App" from the App.razor file as expected. However, I want the Home component to require authorization.
It appears that Blazor is doing some additional routing outside the Router component even though it makes no sense at all.
Can someone explain this strange behaviour and how can I get the Routes component to show the NotAuthorized fragment when I am not authorized?
To enable authorization in the default Blazor Web Template I did the following modifications:
- Install the Microsoft.AspNetCore.Components.WebAssembly.Authentication NuGet package to get the AuthorizeRouteView component and modify the Routes.razor file like in the example shown above.
- Add
builder.Services.AddAuthorizationCore();
in the Program.cs file of the Client project. - Add
builder.Services.AddAuthentication(BearerTokenDefaults.AuthenticationScheme).AddBearerToken();
in the Server project.
You find the complete sample project in my GitHub repository at https://github.com/AntMaster7/BlazorApp3.