首页 > 解决方案 > 使用 HttpContextAccessor 访问 dotnet 3.1 中的登录用户

问题描述

好的,所以我在这里变得不耐烦了。:) 我试图通过访问 IHttpContextAccessor 通过 HttpContext.User 访问我的登录用户,但没有用户可用,也没有任何声明。这里使用的是 Dotnet core 3.1。这基本上是我的理解:使用 HttpContext.SignInAsync(...看到 cookie 正确附加到请求但没有完成一些转换。有谁知道我错过了什么?

            //My controller action:

            var claimsIdentity = new ClaimsIdentity("Application");
            claimsIdentity.AddClaim(emailClaim);
            ... more claims

            await HttpContext.SignInAsync(
                "Application",
                new ClaimsPrincipal(claimsIdentity)
            );


            // Startup.cs:ConfigureServices
            
             services.AddHttpContextAccessor();


            // In a MyClass

            MyClass(IHttpContextAccessor accessor)
            {
                accessor.HttpContext.Claims; // Nothing
            }

标签: .netasp.net-coreauthentication.net-corehttpcontext

解决方案


据我所知,如果我们使用了 cookie 身份验证并且用户已经登录,我们可以从 httpcontext 访问器获取声明。

我建议您可以首先确保浏览器已通过 cookie 将身份验证令牌设置为服务器。

然后我建议您可以确保将 myclass 注入为作用域而不是 Singleton。

更多细节,您可以参考下面的测试代码来读取cookie。

我的课:

public class Myclass
{
    public IHttpContextAccessor _accessor { get; set; }
     public Myclass(IHttpContextAccessor accessor)
    {
        _accessor = accessor;

      var re =  accessor.HttpContext.User.Identity as ClaimsIdentity;
        int i = 0;
    }

    public string GetName() {
        var re = _accessor.HttpContext.User.Identity as ClaimsIdentity;

        string name = re.Claims.First(x => x.Type == "name").Value;

        return name;
    }


}

启动.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
        services.AddHttpContextAccessor();
        services.AddScoped(typeof(Myclass));
    }

用法:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    public Myclass test { get; set; }

    public HomeController(ILogger<HomeController> logger, Myclass _test)
    {
        _logger = logger;
        test = _test;
    }

    public async Task<IActionResult> IndexAsync()
    {
        var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
        claimsIdentity.AddClaim(new Claim("name", "aaaa"));
        await HttpContext.SignInAsync(
           CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(claimsIdentity)
        );
        return View();
    }

    public async Task<IActionResult> PrivacyAsync()
    {
        var  re= test.GetName();

        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

结果:

在此处输入图像描述


推荐阅读