【发布时间】:2020-04-18 12:58:28
【问题描述】:
我已将以下自定义登录添加到默认 Blazor 应用模板的 index.razor(无身份验证)。
<form>
<button @onclick="SignIn">Sign in</button>
</form>
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
private string userName = "FakeUser";
private async Task SignIn(MouseEventArgs e)
{
var fakeUser = new ClaimsPrincipal(new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, userName),
}, "Fake authentication type"));
var provider = (IHostEnvironmentAuthenticationStateProvider)AuthenticationStateProvider;
//provider is ServerAuthenticationStateProvider
provider.SetAuthenticationState(Task.FromResult(new AuthenticationState(fakeUser)));
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
//authState.User.Identity.Name == "Fake User" - this is ok
}
}
但是,当我导航到另一个页面时,authState 不会持久化:
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
//authState.User.Identity.Name == null ??
}
为什么?
【问题讨论】:
标签: authentication blazor blazor-server-side