简体   繁体   中英

Can't obtain guid of the current user

Following this blog and this answer , I'm obtaining the user's name (which seems to be the correct one). However, when I make the call as follows, I get 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"

The user is definitely in the DB and I used the standard registration module in the MVC.NET template. Because of the requirements elsewhere, I need to produce the actual guid and can't use the user's name.

This is a part of my Web.config, which I suspect might be of relevance. I'm not big on security issues.

<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>

First, since you're using the security from the template, you don't have to use Membership . What you need to get is the right type of identity by casting it to ClaimsIdentity . Then, you have access to all the claims for that user.

There's a method for obtaining the name and guid of the current user and you can let intellisense guide you. However, there's much more to the security issue to consider, so if you're curious, keep reading.


There are claims of role, user id, security provider etc. Since all those are collected in a single list, you need to filter out those that are appropriate in your case. As help, you have string fields, eg RoleClaimType and NameClaimType for the commonly requested claims.

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

Also, note that in basic cases (with a single identity for claims), there's ClaimsPrincipal that's more recommneded to apply (it also has Claims property).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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