aspnet / Identity

[Archived] ASP.NET Core Identity is the membership system for building ASP.NET Core web applications, including membership, login, and user data. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.96k stars 870 forks source link

ClaimsIdentity.UserIdClaimType not found in httpcontext Principal even though Principal.Identity != null #1903

Closed guylando closed 5 years ago

guylando commented 6 years ago

We have some rare situations where during ValidatePrincipalAsync, even though the httpcontex has context.Principal != null && context.Principal.Identity != null still context.Principal.FindFirstValue(identityOptions.ClaimsIdentity.UserIdClaimType) returns null. I think it happens in the first ajax requests after a user hasn't been active for a long time (website is hosted on kestrel behind iis so server process dies when no requests are received for a long time so maybe when first ajax request creates a new process it might happen?). Does it make sense? I dont like to add "if (xxx != null)" just to avoid an exception but without understanding why it gets null value. Can you please explain this situation of how the user id claim is null even though the prinicpal identity is not null?

blowdart commented 6 years ago

How are you authenticating your ajax call? Cookies? JWT?

guylando commented 6 years ago

cookies

blowdart commented 6 years ago

When you get the principal back is it actually the identity you expect? Did the cookie expire in any way?

guylando commented 6 years ago

context of type CookieValidatePrincipalContext which is received in our custom ValidatePrincipalAsync has context.Principal.Identity != null and yet context.Principal.FindFirstValue(identityOptions.ClaimsIdentity.UserIdClaimType) is null (I had a mistake in original issue description where I wrote its SecurityStampClaimType when its actually UserIdClaimType).

I don't have any other information because this issue can't be easily reproduced to give this information. If the cookie expired or the server restarted or whatever, can it cause context.Principal.Identity != null while context.Principal not having UserIdClaimType?

Thanks

blowdart commented 5 years ago

Without a repo there's nothing we can do here unfortunately. There is a default context.Principal which is empty and returns false for IsAuthenticated() which would explain why you get a non-null Principal with no claims you expect.