Search code examples
c#windows-authentication

What does Principal.Identity.GetUserId<int>() return?


I have come across the following code, and I am trying to work out exactly what it does.

if (principal.Identity is WindowsIdentity)
{
    profile = //generate a profile somehow
}
....
var userId = principal.Identity.GetUserId<int>();

this is what I (think) I understand:

principal 

is the currently logged in user

this line:

if (principal.Identity is WindowsIdentity)

checks if the currently logged in user is a windows user eg logged in through windows auth

This line is the line I am having trouble with.

var userId = principal.Identity.GetUserId<int>();

If we assume from here that all users are windows users, this line seems to be getting the user ID.

The part I am not sure about is whether this is obtaining the windows userID, or the userID assigned within my application? Do windows users even have userID?

My problem is that this always returns 0, and I cannot work out why?

If it relates to the users ID within the application, I assume this needs to be mapped or assigned somewhere, but again I cannot see how.

I have been on this problem most of the day but for all my googling I cannot make any progress...


Solution

  • So this is the decompiled source (according to resharper) for the GetUserId extension method

    if (identity == null)
        throw new ArgumentNullException("identity");
    ClaimsIdentity identity1 = identity as ClaimsIdentity;
    if (identity1 != null)
    {
      string firstValue = IdentityExtensions.FindFirstValue(identity1, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier");
      if (firstValue != null)
          return (T) Convert.ChangeType((object) firstValue, typeof (T), (IFormatProvider) CultureInfo.InvariantCulture);
    }
    return default (T);
    

    WindowsIdentity will pass the safe cast as ClaimsIdentity since it inherits from it

    So it comes down whether or not your windows identity contains a claim for http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier

    If you're getting 0, you don't have that claim