如何在 Blazor 服务器端(Razor 组件)中实现身份验证。我正在使用 .net 3 preview 5。我目前正在使用 AspNetCore.Identity。注册用户工作正常,但调用任何 SignIn 方法都会导致异常(响应已启动)。
这是一些代码 - 它唯一的玩具/原型,所以它有点混乱/破解在一起。一旦我向自己证明它实际上可以使用 Identity 和 Blazor 服务器端,将重写!
@page "/signup"
@using System.Security.Claims
@using AuthProto.Data
@using AuthProto.Entities
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Authentication.Cookies
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Http.Extensions
@using Microsoft.AspNetCore.Identity
@using Microsoft.AspNetCore.Identity.EntityFrameworkCore
@inject WeatherForecastService ForecastService
@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager
@inject UserDb db;
<h1>Signup</h1>
<h2>@message</h2>
<EditForm Model="@data" OnValidSubmit="@HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="name" bind-Value="@data.Email" />
<InputText id="password" bind-Value="@data.Password" />
<button type="submit">Submit</button>
</EditForm>
<h2>Login</h2>
<EditForm Model="@login" OnValidSubmit="@HandleLogin">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText id="name" bind-Value="@login.email" />
<InputText id="password" bind-Value="@login.password" />
<button type="submit">Submit</button>
</EditForm>
@functions {
private SignupApi data = new SignupApi();
private LoginApi login = new LoginApi();
private string message;
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
private void HandleValidSubmit()
{
var user = new AppUser() { Email = data.Email, UserName = data.Email };
IdentityResult result = UserManager.CreateAsync(user, data.Password).Result;
if (result.Succeeded)
{
message = string.Format("User {0} was created successfully!", user.UserName);
// var signInResult = SignInManager.PasswordSignInAsync(
// user, data.Password, false, false).Result;
}
else
{
message = result.Errors.FirstOrDefault()?.Description;
}
}
private async void HandleLogin()
{
var x = db.Users.SingleOrDefault(u => u.Email == data.Email);
var result = SignInManager.CheckPasswordSignInAsync(x, data.Password, true).Result;
await SignInManager.SignInAsync(x, true);
}
}
我也尝试过使用 HttpAssessor 手动访问 HttpContext.SigninAsync - 没有例外,但没有设置 cookie。
我猜问题是 Identity 当前与 Blazor 服务器端不兼容,并且 SignIn 方法因此类似于启动响应,然后在稍后的调用中添加到它。我认为这会导致 SignalR 与客户端通信出现问题。