Blazor Cookie身份验证

问题描述 投票:0回答:1

[请帮助我,我不知道有什么问题,我一直在努力寻找一些东西...

我想在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信息。

有人可以帮我吗?我需要一个身份验证和授权系统,该系统可以向我提供有关用户的需求信息。

我将非常感谢您的帮助

谢谢

authentication cookies authorization blazor
1个回答
0
投票

这是Blazor服务器还是Blazor WebAssembly?

无论如何,您不能在您的应用程序中使用HttpContextAccessor。

_httpContextAccessor.HttpContext.SignInAsync无法使用,因为HttpContext在Blazor Server中不可用。不用说不能在浏览器上创建HttpContext ...

要么使用此:services.AddHttpClient();

使用IHttpClientFactory(推荐)

或此:services.AddScoped<HttpClient>();

在我看来,您对Blazor或Blazor的身份验证和授权系统都不熟悉。我建议您查阅文档并学习如何使用它们。它们非常好,可以为您节省大量的硬编码时间。

希望这有帮助...

© www.soinside.com 2019 - 2024. All rights reserved.