【问题标题】:Get Current User ASP.NET Visual Studio 2013 Preview ClaimsPrinciple获取当前用户 ASP.NET Visual Studio 2013 Preview ClaimsPrincipal
【发布时间】:2013-09-10 16:36:48
【问题描述】:

我正在尝试使用新的 Visual Studio 2013 Preview for Web 让当前用户进入 Web 表单项目。我可以使用 Page.User 获取用户名,但试图获取用户 ID 是我卡住的地方。它正在使用他们提出的这种新的身份模型。

这就是我所拥有的:

//Gets the correct username
string uname = User.Identity.Name;
//Returns a null object
Microsoft.AspNet.Identity.IUser user = IdentityConfig.Users.Find(uname);
//What I hope to call to add a user to a role
IdentityConfig.Roles.AddUserToRole("NPO", user.Id);

【问题讨论】:

  • 你能显示一些代码吗?
  • 对不起,是的。现在有示例代码。

标签: asp.net webforms claims-based-identity visual-studio-2013 asp.net-identity


【解决方案1】:

如果您使用的是 ASP.NET WebForms 模板附带的默认成员资格,您应该执行以下操作来检索用户:

if (this.User != null && this.User.Identity.IsAuthenticated)
{
  var userName = HttpContext.Current.User.Identity.Name;
}

你说的新型号是ClaimsPrincipal。唯一的区别是Claims Based Secury,它与旧版本完全兼容,但功能更强大。

编辑:

要将用户添加到某些Role 编程,您应该这样做,传递用户名和角色名:

if (this.User != null && this.User.Identity.IsAuthenticated)
{
  var userName = HttpContext.Current.User.Identity.Name;
  System.Web.Security.Roles.AddUserToRole(userName, "Role Name");    
}

使用新的基于声明的安全性

if (this.User != null && this.User.Identity.IsAuthenticated)
{
  var userName = HttpContext.Current.User.Identity.Name;
  ClaimsPrincipal cp = (ClaimsPrincipal)HttpContext.Current.User;

  GenericIdentity genericIdentity;
  ClaimsIdentity claimsIdentity;
  Claim claim;

  genericIdentity = new GenericIdentity(userName, "Custom Claims Principal");

  claimsIdentity = new ClaimsIdentity(genericIdentity);

  claim = new Claim(ClaimTypes.Role, "Role Name");
  claimsIdentity.AddClaim(claim);

  cp.AddIdentity(claimsIdentity);
}

【讨论】:

  • 太好了,我很高兴知道它现在叫什么。唯一的问题是如何将用户添加到角色? Roles.AddUserToRole 函数需要 ID。我好像没找到。
  • 好的...那么,我如何获取与用户关联的所有角色?假设我想根据文件夹或文件所属的角色限制对它们的访问?
  • 我不能只使用角色类,因为 RoleManager 默认是禁用的,对吧?
【解决方案2】:

默认情况下,用户 ID 存储在 ClaimTypes.NameIdentifier 声明中。我们还提供了一个扩展方法,它存在于 Microsoft.AspNet.Identity 中,因此您可以简单地调用 Page.User.Identity.GetUserId(),而不是仅仅为了获取 id 而获取用户。

【讨论】:

  • 绝对不适合我。我有一个声明身份,但 GetUserId() 返回 null。用户表上的主键是一个 GUID。
【解决方案3】:

只是为今天发现此内容的人发布的帖子,现在很容易完成

ApplicationUserManager manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationSignInManager signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
ApplicationUser user = signinManager.UserManager.FindByNameAsync("username").Result;

此时您可以访问所有 ID、电子邮件、电话号码,甚至用户密码的哈希版本。

【讨论】:

    猜你喜欢
    • 2013-08-12
    • 2013-07-16
    • 2015-03-15
    • 1970-01-01
    • 2014-11-28
    • 2014-01-25
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多