请帮助我,我不知道有什么问题,我已经尝试了好几个小时了...
我想在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信息。
有人可以帮助我吗?我需要一个身份验证和授权系统,该系统可以向我提供有关用户的需求信息。
感谢您的帮助
谢谢
答案 0 :(得分:0)
这是Blazor服务器或Blazor WebAssembly吗?
无论如何,您都不能在应用程序中使用HttpContextAccessor。
此_httpContextAccessor.HttpContext.SignInAsync
无法使用,因为HttpContext在Blazor Server中不可用。
不用说不能在浏览器上创建HttpContext ...
可以使用以下命令:services.AddHttpClient();
使用IHttpClientFactory(推荐)
或此:services.AddScoped<HttpClient>();
在我看来,您对Blazor或Blazor的身份验证和授权系统都不熟悉。我建议您查阅文档并学习如何使用它们。它们非常好,可以为您节省大量的硬编码时间。
希望这对您有帮助...