我在默认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 ??
}
为什么?
答案 0 :(得分:2)
我运行了您的代码,它确实保留了身份验证状态...
这是我的代码:
@page "/"
@using System.Security.Claims;
<button @onclick="SignIn">Sign in</button>
@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();
Console.WriteLine(authState.User.Identity.Name);
}
}
@page "/counter"
@inject AuthenticationStateProvider AuthenticationStateProvider
@code {
protected override async Task OnInitializedAsync()
{
var authState = await
AuthenticationStateProvider.GetAuthenticationStateAsync();
Console.WriteLine(authState.User.Identity.Name);
}
}
请运行您的应用程序,单击按钮元素,然后按NavMenu中的“ Counter”菜单项以导航到Counter组件...现在转到“输出”窗口,查看单词FakeUser是否已打印两次。
答案 1 :(得分:1)
问题在于,<button>
元素位于本机<form>
内,因为它提交了表单(重新加载页面)
<form>
<button @onclick="SignIn">Sign in</button>
</form>
解决方案:
使用<EditForm>或
<button type="button" @onclick="SignIn">Sign in</button>