![](/img/trans.png)
[英]blazor server authentication dont work with httpcontext cookie
[英]Blazor cookie authentication
请帮助我,我不知道有什么问题,我一直在努力寻找几个小时的东西......
我想在 blazor 的 cookie 上有一个用户登录组件。 我需要在我的应用程序的所有位置从 cookie 中获取信息的可能性。
在我的Startup.cs
中,我添加了ConfigureServices
:
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddHttpContextAccessor();
services.AddScoped<HttpContextAccessor>();
services.AddHttpClient();
services.AddScoped<HttpClient>();
在端点之前配置
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
然后在应用程序中,我编写了代码以进行登录
public async Task Login()
{
var claims = new List<Claim> {
new Claim(ClaimTypes.Name, "1", ClaimValueTypes.String),
new Claim(ClaimTypes.Surname, "2", ClaimValueTypes.String),
new Claim(ClaimTypes.Country, "3", ClaimValueTypes.String),
new Claim("4", "4.1", ClaimValueTypes.String)
};
var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false
};
var userPrincipal = new ClaimsPrincipal(userIdentity);
await _httpContextAccessor.HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
userPrincipal);
}
但我的浏览器中没有 cookie,代码/控制台中没有错误。
当我查看状态时
var z= _httpContextAccessor.HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
userPrincipal).Status
然后我得到一个错误
System.Threading.Tasks.TaskStatus.Faulted 信息。
有谁能够帮我? 我需要一个身份验证和授权系统,可以按需提供有关用户的信息。
我将不胜感激
谢谢你
这是 Blazor 服务器还是 Blazor WebAssembly?
在任何情况下,您都不能在您的应用程序中使用 HttpContextAccessor。
此_httpContextAccessor.HttpContext.SignInAsync
无法工作,因为 HttpContext 在 Blazor 服务器中不可用。 不用说 HttpContext 不能在浏览器上创建...
要么使用这个: services.AddHttpClient();
使用 IHttpClientFactory(推荐)
或者这个: services.AddScoped<HttpClient>();
在我看来,您对 Blazor 或 Blazor 的身份验证和授权系统都不熟悉。 我建议您查阅文档并学习如何使用它们。 它们非常好,可以为您节省大量的硬编码时间。
希望这可以帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.