如何将身份验证 SignInAsync 用作来自剃须刀组件的调用。由于上下文处于管道的后期状态,它似乎会引发一些错误。
调用 HttpContext.SignInAsync 时出错:
System.AggregateException: 'One or more errors occurred. (The response headers cannot be modified because the response has already started.)'
InvalidOperationException: The response headers cannot be modified because the response has already started.
这是实现 SignIn 的 UserState.cs。
public class UserState
{
readonly IHttpContextAccessor Context;
public UserState(IHttpContextAccessor Context)
{
this.Context = Context;
}
public string DisplayName { get; set; }
public ClaimsPrincipal User => Context.HttpContext.User;
public bool IsLoggedIn => User?.Identity.IsAuthenticated ?? false;
public void SignIn()
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "Bob", ClaimValueTypes.String),
new Claim(ClaimTypes.Surname, "Builder", ClaimValueTypes.String),
};
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var userPrincipal = new ClaimsPrincipal(userIdentity);
Context.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = true,
AllowRefresh = true
}).Wait();
}
}
方法被调用并注入如下:
@page "/"
@inject UserState User
@if (User.IsLoggedIn)
{
<p>You are logged in</p>
} else {
<p>You are NOT logged in</p>
}
<button onclick="@User.SignIn">Login</button>
有没有办法登录获得成功响应,然后从 SignIn 方法刷新页面。
我见过一些使用 MVC 控制器的类似实现。不涉及 mvc 就没有办法调用身份验证请求吗?