Search code examples
asp.netwebformsclaims-based-identityvisual-studio-2013asp.net-identity

Get Current User ASP.NET Visual Studio 2013 Preview ClaimsPrinciple


I'm trying to get the current user in a web forms project using the new Visual Studio 2013 Preview for Web. I'm able to get the username using Page.User, but trying to get the user id is where I'm stuck. It's using this new Identity Model thing they've come out with.

This is what I've got:

//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);

Solution

  • If you are using the Default Membership that come's with the ASP.NET WebForms Template you should do something like this to retrieve the user:

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

    The new model you are talking about is ClaimsPrincipal. The unique difference is this Claims Based Secury, that is completly compatible with the older versions but more powerfull.

    EDIT:

    To add an user to some Role programaticaly you should do this, passing the user name and the role name:

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

    Using the new Claim Based Security

    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);
    }