Search code examples
c#asp.net-coreasp.net-identityidentityserver4asp.net-core-3.1

How to access claims from HttpContext in .Net Core?


Using below code to signIn with custom claims and it's working fine.

    private async Task SignInAsync(ApplicationUser user)
    {
        var claims = await _claimsPrincipalFactory.CreateAsync(user);

        claims.Identities.First().AddClaims(new[]
        {
            new Claim("xxx", "111"),
            new Claim("yyy", "222")
        });

        await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claims);
    }

but when trying to access using HttpContext in service like below

var claims = HttpContext.User.Identities.FirstOrDefault().Claims.ToList();

it returns 0 claims.

Please help.


Solution

  • Finally here is working code.

            services.ConfigureApplicationCookie(options =>
            {
                options.Events.OnSignedIn = (context) =>
                {
                    context.HttpContext.User = context.Principal;
                    return Task.CompletedTask;
                };
            });