I added @attribute [Authorize (Roles="Administrator")] in test.razor component, Non Administrator role error when logging in.
Error Info:
An unhandled exception occurred while processing the request.
InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action configureOptions).
Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties)
I hope to be automatically redirected to the Login page when not logged in as an Administrator Roles.
test.razor:
@page "/test"@attribute [Authorize(Roles = "Administrator")]<PageTitle>Test</PageTitle>Routes.razor:
<Router AppAssembly="typeof(App).Assembly"><Found Context="routeData"><AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" /><FocusOnNavigate RouteData="routeData" Selector="h1" /></Found></Router>MainLayout.razor:
<AuthorizeView><NotAuthorized> @if (!context.User.Identity!.IsAuthenticated) {<Login /> } else {<p>You do not have permission to access resources.</p> }</NotAuthorized><AuthorizeView></AuthorizeView>CustomAuthStateProvider.cs
using System.Security.Claims;using Microsoft.AspNetCore.Components.Authorization;public class CustomAuthStateProvider : AuthenticationStateProvider{ public override Task<AuthenticationState> GetAuthenticationStateAsync() { var identity = new ClaimsIdentity( [ new Claim(ClaimTypes.Name, "test"), new Claim(ClaimTypes.Role, "user") ], "Custom Authentication"); var user = new ClaimsPrincipal(identity); return Task.FromResult(new AuthenticationState(user)); }}Program.cs:
builder.Services.AddAuthorization(); builder.Services.AddCascadingAuthenticationState();builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthStateProvider>();app.UseAuthentication();app.UseAuthorization();app.UseAntiforgery();Can anyone help me? Thank you