我已经创建了一个名为CustomAuthenticationStateProvider的类,它继承自身份验证状态提供程序。现在它是测试的基础,但我将在稍后从本地存储中的JWT读取它以进行声明。
代码如下:
public class CustomAuthenticationStateProvider : AuthenticationStateProvider
{
private ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
private ClaimsPrincipal _user = new ClaimsPrincipal(new ClaimsIdentity());
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
return Task.FromResult(new AuthenticationState(_user));
}
public void Login()
{
//make claims for an admin user and return that as the authentication state
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "Jeff"),
new Claim(ClaimTypes.Role, "Admin")
};
var identity = new ClaimsIdentity(claims, "Custom");
_user = new ClaimsPrincipal(identity);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public void Logout()
{
_user = _anonymous;
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
字符串
Here is my app.剃刀
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
型
在我的program.cs中有:builder.Services.AddScoped<CustomAuthenticationStateProvider, CustomAuthenticationStateProvider>(); builder.Services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthenticationStateProvider>());
和app.UseAuthentication(); app.UseAuthorization();
个
为了测试我的导航栏,我把这个:
<AuthorizeView>
<Authorized>
Auth
</Authorized>
<NotAuthorized>
Not Auth
</NotAuthorized>
</AuthorizeView>
型
我试着在一个新的blazor服务器应用程序中实现同样的代码,它似乎像预期的那样工作。在那个应用程序中,我可以在GetAuthenticationStateAsync()中的返回处设置一个断点,当应用程序启动时,它会中断,这不是我一直在工作的实际应用程序的情况。除非我调用登录退出logout函数,否则GetAuthenticationStateAsync()永远不会被调用。
1条答案
按热度按时间t98cgbkg1#
我发现我的问题在于
字符串
我把它放在了
型
我想它需要在之后才能正常工作。
希望这能帮助其他人,如果他们遇到同样的问题。