繁体   English   中英

无法获取当前用户的GUID

[英]Can't obtain guid of the current user

遵循此博客此答案之后 ,我将获得用户的名称(似乎是正确的名称)。 但是,当我按如下方式进行呼叫时,得到null

MembershipUser uno = Membership.GetUser(); //null
MembershipUser duo = Membership.GetUser(User.Identity.Name); // null
bool           tri = User.Identity.IsAuthenticated; // true
string         qua = User.Identity.AuthenticationType; // "ApplicationCookie"

用户肯定在数据库中,并且我在MVC.NET模板中使用了标准注册模块。 由于其他地方的要求,我需要生成实际的Guid,并且不能使用用户名。

这是我的Web.config的一部分,我怀疑这可能是相关的。 我在安全问题上并不大。

<system.web>
  <authentication mode="None" />
  <compilation debug="true" targetFramework="4.5.2" />
  <customErrors mode="Off"></customErrors>
  <httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
  <modules>
    <remove name="FormsAuthentication" />
  </modules>
</system.webServer>

首先,由于您使用的是模板中的安全性,因此不必使用Membership 您需要通过将其强制转换为ClaimsIdentity来获得正确的身份类型。 然后,您可以访问该用户的所有声明。

有一种获取当前用户的名称和GUID的方法,您可以让intellisense指导您。 但是,还有很多安全问题需要考虑,因此,如果您好奇,请继续阅读。


其中包含角色,用户ID,安全提供者等声明。由于所有这些声明都收集在一个列表中,因此您需要过滤出适合您情况的声明。 作为帮助,您可以使用字符串字段,例如用于常见请求声明的RoleClaimTypeNameClaimType

var identity = User.Identity as ClaimsIdentity;
var roles = identity.Claims
  .Where(c => c.Type == identity.RoleClaimType)
  .Select(c => c.Value);

另外,请注意,在基本情况下(具有唯一的索赔标识), ClaimsPrincipal使用ClaimsPrincipal(它也具有Claims属性)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM