简体   繁体   English

如何在逻辑层访问 ClaimsIdentity

[英]How can acces ClaimsIdentity on Logic Layer

I want to move this service to logic for using on everywhere, but i can't successful because it was coming from the controller.我想将此服务转移到逻辑上以便在任何地方使用,但我无法成功,因为它来自 controller。

I have two services.我有两个服务。 There read caches and I use them in the controller layer when authenticating.有读取缓存,我在验证时在 controller 层中使用它们。

my first logic is reading companyId in cache我的第一个逻辑是在缓存中读取 companyId

     public virtual int GetCompanyIdFromCache(int id)
    {
        _memCache.TryGetValue(id, out int companyId);
        return companyId;
    }

My second service is also on the controller.我的第二个服务也在 controller 上。 (helps me find the user's id) (帮助我找到用户的 id)

[HttpGet]
    [Route("GetCompanyId")]
    public int GetCompanyPublicId()
    {
        if (User.Identity is ClaimsIdentity claimsIdentity)
        {
            var userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
            var companyId = _userService.GetCompanyIdFromCache(Convert.ToInt32(userId));
            return companyId;
        }

        throw new ArgumentException("Can't be found Company");
    }

I want to use this method everywhere, so i want to move the second service completely to logic layer but User field comes from ControllerBase (on HttpContext i guess) and I can't move it to logic我想在任何地方都使用这种方法,所以我想将第二个服务完全移动到逻辑层,但用户字段来自 ControllerBase(我猜是在 HttpContext 上),我无法将它移动到逻辑层

if (User.Identity is ClaimsIdentity claimsIdentity)

What should I do to refactor the logic layer?我应该怎么做来重构逻辑层?

As far as I know, the User.Identity is ClaimsIdentity which is a property in the controllerbase.据我所知, User.Identity 是 ClaimsIdentity ,它是控制器库中的一个属性。 We couldn't directly use it in the other methods.我们不能直接在其他方法中使用它。

If you want to access the User.Identity in other service method, I suggest you could try to inject the httpaccessor service and get the ClaimsIdentity from it.如果您想在其他服务方法中访问 User.Identity,我建议您可以尝试注入 httpaccessor 服务并从中获取 ClaimsIdentity。

More details, you could refer to below codes:更多细节,您可以参考以下代码:

Create myclass:创建我的类:

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;
    }
}

Startup.cs:启动.cs:

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

Usage:用法:

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 });
    }
}

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM