如何在Blazor服务器端(Razor组件)中实现身份验证。我使用的是.net 3预览版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 Server端和SignIn方法不兼容,比如启动响应,然后在调用中添加。我认为这会导致与客户端的SignalR通信出现问题。
发布于 2019-10-09 17:57:34
身份包含在Blazor项目模型中,所以我认为这是进行身份验证的好方法。因此,您仍然需要一个C#类SignInManager来提供您的身份验证行为(它必须在Startup.cs文件中的ConfigureService方法中设置),因为它继承自SignInManager接口,它有一个对应于HttpContext的上下文属性。它可以用来携带ClaimsPrincipal和cookies的详细信息。不过,对于cookies,您需要在Startup.cs中添加良好的服务:
service.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);Startup.cs exemple我用它创建了一个新的应用程序,其中不使用数据库进行身份验证,并且它可以工作。
https://stackoverflow.com/questions/56207811
复制相似问题