Principal.Identity.GetUserId <int>()返回什么?

时间:2017-01-03 16:57:57

标签: c# windows-authentication

我遇到了以下代码,我正在努力弄清楚它的作用。

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

这就是我(我想)的理解:

principal 

是当前登录的用户

这一行:

if (principal.Identity is WindowsIdentity)

检查当前登录的用户是否是Windows用户,例如通过windows auth登录

此行是我遇到问题的行。

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

如果我们从这里假设所有用户都是Windows用户,则此行似乎是获取用户ID。

我不确定的部分是获取windows userID,还是在我的应用程序中分配的userID? Windows用户甚至拥有userID吗?

我的问题是这总是返回0,我无法找出原因?

如果它与应用程序中的用户ID有关,我认为这需要在某处映射或分配,但我再也看不到。

我一天中大部分时间都在讨论这个问题,但是对于我所有的谷歌搜索我都无法取得任何进展......

1 个答案:

答案 0 :(得分:1)

所以这是GetUserId扩展​​方法的反编译源(根据resharper)

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将从it inherits from it

开始通过安全演员as ClaimsIdentity

因此,对于http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier

,您的窗口是否会contains a claim

如果您获得0,则表示您没有该声明