【发布时间】:2023-03-25 23:22:02
【问题描述】:
我有一个非常基本的 blazor 项目设置,通过实现 AuthenticationStateProvider 来通过自定义身份验证机制测试授权。
我伪造了授权状态以始终返回伪造的登录用户并将@attribute [Authorized] 添加到我的可路由页面组件,但导航到时它始终显示“未授权”消息。
首先在 Startup.cs 中添加必要的初始化
app.UseAuthentication();
app.UseAuthorization();
我已经实现了一个自定义的 AuthenticationStateProvider,它总是返回一个登录的用户:
public class LocalStorageAuthenticationStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "user@fake.com","apiauth_type_email")
});
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
..我已经注册了我的自定义提供程序:
services.AddScoped<AuthenticationStateProvider, LocalStorageAuthenticationStateProvider>();
..我已将 AuthorizeRouteView 添加到 App.razor
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
最后,我将授权属性添加到我的可路由页面:
@page "/personal/dashboard"
@attribute [Authorize]
但是当我导航到那里时,我总是会收到“未授权”的消息。我在这里错过了什么?
【问题讨论】:
标签: authentication authorization blazor blazor-server-side blazor-webassembly