Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c# - 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.

I have two services. There read caches and I use them in the controller layer when authenticating.

my first logic is reading companyId in cache

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

My second service is also on the controller. (helps me find the user's 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

if (User.Identity is ClaimsIdentity claimsIdentity)

What should I do to refactor the logic layer?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As far as I know, the User.Identity is ClaimsIdentity which is a property in the controllerbase. 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.

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:

    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:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...