ASP.NET (OWIN) Identity: How to get UserID from a Web API controller?

后端 未结 5 1729
野趣味
野趣味 2020-11-30 03:33

(Using VS2013 RTW, ASP.NET MVC5)

I\'ve seen lots of documentation on how to add properties to the ApplicationUser class (and table) when using ASP.NET identity. But

相关标签:
5条回答
  • 2020-11-30 04:07

    You should be able to get user id on both MVC controller and web api controller by same extension method in identity 1.0 RTW package.

    Here is the extensions from identity package:

    namespace Microsoft.AspNet.Identity
    {
        public static class IdentityExtensions
        {
            public static string FindFirstValue(this ClaimsIdentity identity, string claimType);
            public static string GetUserId(this IIdentity identity);
            public static string GetUserName(this IIdentity identity);
        }
    }
    

    The IIdentity is the base interface for all identity types. You may need to add "using Microsoft.AspNet.Identity" in order to see the extension method.

    BTW: regarding adding a foreign table for user, why not using ApplicationUser and add navigation property to UserPreference to let EF to handle their relationship? That will be easier.

    0 讨论(0)
  • 2020-11-30 04:11

    Tried @Mastenka answer and it gave me nothing. I checked ClaimsIdentity and there were claims type "UserName", so as a result, I get username by using "UserName" as ClaimsType. Hope someone will give more info about it. It looks strange that "ClaimTypes.NameIdentifier" had no effect. (ApiController, ASP MVC API)

    var userName = ((ClaimsIdentity)RequestContext.Principal.Identity).Claims.FirstOrDefault(cl => cl.Type == "UserName")?.Value;
    
    0 讨论(0)
  • 2020-11-30 04:17

    Short description for the best answer:

    1. Install-Package Microsoft.AspNet.Identity.Core -Version 2.2.1
    2. var userId = User.Identity.GetUserId();
    0 讨论(0)
  • 2020-11-30 04:24
    ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
    identity.AddClaim(new Claim(ClaimTypes.Name, userName));
    identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, UserID));
    

    ClaimTypes.NameIdentifier is the claim for the function User.Identity.GetUserId()

    0 讨论(0)
  • 2020-11-30 04:25

    I'm using claim base approach:

    private ApplicationUser GetCurrentUser(ApplicationDbContext context)
    {
      var identity = User.Identity as ClaimsIdentity;
      Claim identityClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
    
      return context.Users.FirstOrDefault(u => u.Id == identityClaim.Value);
    }
    
    0 讨论(0)
提交回复
热议问题