我有一個非常基本的 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, "[email protected]","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]
但是當我在那里導航時,我總是遇到“未授權”訊息。我在這里缺少什么?
uj5u.com熱心網友回復:
你的問題在這里:
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "[email protected]","apiauth_type_email")
});
您有拼寫錯誤并且沒有提供authenticationTypefor ClaimsIdentity。您的代碼應如下所示:
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Email, "[email protected]")
}, "apiauth_type_email");
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/343244.html
標籤:验证 授权 西装外套 blazor 服务器端 blazor-webassembly
