我已经尝试过为上面的.Net 3制作的这个,但它不起作用:
builder.Services.AddAuthorization(options =>
{
options.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
});
很抱歉,我还应该提到,如果用户没有通过身份验证,我想自动重定向到登录页面。
CCD_ 1将仅通过说"是"来阻止访问;未授权";但我希望用户重定向到登录页面
在_Imports.razor文件中添加@attribute [Authorize]
后,这就是显示的内容
在此处输入图像描述
我相信这会奏效。。。将以下代码段放在_Imports.razor文件中
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
在这种情况下,当"索引"页面被点击时,用户将被重定向到"登录"页面。如果您想在Blazor应用程序渲染之前执行身份验证,请在_Host.cshtml文件中添加上面的代码片段
将@attribute [AllowAnonymous]
添加到要从身份验证中排除的特定页面,例如Index页面。
更新:以下描述了如果用户未通过身份验证,如何强制自动显示登录页面:
扩展AuthorizeRouteView
组件,驻留在应用程序组件中,如下所示:
<AuthorizeRouteView RouteData="@routeData"
DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@{
NavigationManager.NavigateTo("identity/account/login",
forceLoad: true);
}
</NotAuthorized>
<Authorizing>
Wait...
</Authorizing>
</AuthorizeRouteView>
如果用户未被授权查看登录页面,则上面的代码会将其导航到登录页面。警告用户可能已通过身份验证,但仍然没有被授权查看特定页面。您的代码应该验证用户是否已通过身份验证,如果他通过了身份验证,请让他知道他无权查看当前页面。如果他没有通过身份验证,请将他发送到登录页面。请注意,基本授权只要求对用户进行身份验证。
以下是App.razor组件的完整代码:
@inject NavigationManager NavigationManager
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData"
DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@{
NavigationManager.NavigateTo("identity/account/login",
forceLoad: true);
}
</NotAuthorized>
<Authorizing>
Wait...
</Authorizing>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
只需在_Import.razor文件中添加@attribute [Authorize]
。
此时,如果您需要一些没有登录的页面,请添加@attribute [AllowAnonymous]