Ravi
Ravi

Reputation: 448

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.

Upvotes: 5

Views: 6334

Answers (4)

recep nedim Donmez
recep nedim Donmez

Reputation: 1

if (access token in header or query parameter)
{
    // Set the claims like in the Account/Login action from the interactive login form
    var claims = ...;
    // Local helper method, is used in other places, too
    var claimsIdentity = await SignInAsync(httpContext, claims, false);
    // Set user for the current request
    // This works in that it's in User.Identity, but the auth events won't fire
    httpContext.User = new ClaimsPrincipal(claimsIdentity);
}

Upvotes: 0

Ravi
Ravi

Reputation: 448

Finally here is working code.

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

Upvotes: 0

weichch
weichch

Reputation: 10055

It depends on the implementation of the schema, the authentication handler may not update HttpContext.User by default.

For example, the cookie authentication handler does not sign the current user in, instead, it only generates authentication ticket and sets it to response.

SignInAsync creates an encrypted cookie and adds it to the current response. If AuthenticationScheme isn't specified, the default scheme is used.

If you are using cookie authentication, you could handle CookieAuthenticationEvents.OnSignedIn event to update HttpContext.User:

.AddCookie(IdentityConstants.ApplicationScheme,
    opt =>
    {
        opt.Events = new CookieAuthenticationEvents
        {
            OnSignedIn = async ctx =>
            {
                ctx.HttpContext.User = ctx.Principal;
            }
        };
    });

Upvotes: 2

user4864425
user4864425

Reputation:

My assumption was that the claims were missing due to the order of the statements that build the pipeline.

In Configure you can insert middleware to the pipeline. When inserting middleware, the order is important, unlike in ConfigureServices where it's not.

So when a service is used in middleware that uses the claims before the user is authenticated, then the claims are not available yet, e.g.:

app.UseMyMiddlewareThatCallsService(); 
app.UseAuthentication();

But when the order is changed, the claims are.

app.UseAuthentication();
app.UseMyMiddlewareThatCallsService(); 

Upvotes: 2

Related Questions