在我的 blazor 服务器应用程序中,我创建了一个自定义的authenticationStateProvider 来从我自己的数据库验证用户。它工作正常。但在我的 app.razor 页面中,我设置了 NotAuthorized 标记以将匿名用户重定向到登录页面,但不起作用。这是我的 app.razor 页面代码:
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly" AdditionalAssemblies="@_loadedAssemblies">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<RedirectToLoginPage />
</NotAuthorized>
<Authorizing>
<span class="persianFontSans">Authorizing ...</span>
</Authorizing>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>The page not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<NotFound />
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
这是我的 customAuthenticationProvider 类:
public class SmartMISAuthenticationStateProvider : AuthenticationStateProvider
{
private readonly ProtectedSessionStorage _sessionStorage;
private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
public SmartMISAuthenticationStateProvider(ProtectedSessionStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var accountInfoStorageResult = await _sessionStorage.GetAsync<AccountInfo>("_accountSession");
var accountInfoSession = accountInfoStorageResult.Success ? accountInfoStorageResult.Value : null;
if (accountInfoSession == null)
return await Task.FromResult(new AuthenticationState(_anonymous));
var claims = new List<Claim>();
claims.Add(new Claim("AccountID", accountInfoSession.AccountID));
claims.Add(new Claim("AccountType", accountInfoSession.AccountType));
claims.Add(new Claim(ClaimTypes.Name, accountInfoSession.FullName));
claims.Add(new Claim(ClaimTypes.MobilePhone, accountInfoSession.PhoneNumber));
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "SmartMISAuth"));
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
catch (Exception ex)
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
}
public async Task UpdateAuthenticationStateAsync(AccountInfo accountInfo)
{
ClaimsPrincipal claimsPrincipal;
if (accountInfo != null)
{
await _sessionStorage.SetAsync("_accountSession", accountInfo);
var claims = new List<Claim>();
claims.Add(new Claim("AccountID", accountInfo.AccountID));
claims.Add(new Claim("AccountType", accountInfo.AccountType));
claims.Add(new Claim(ClaimTypes.Name, accountInfo.FullName));
claims.Add(new Claim(ClaimTypes.MobilePhone, accountInfo.PhoneNumber));
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims));
}
else
{
await _sessionStorage.DeleteAsync("_accountSession");
claimsPrincipal = _anonymous;
}
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
}
问题出在哪里,如何解决? 预先感谢