我需要从Asp.Net用户授权系统获取UserId,因为我的大部分数据都存储在SQL中,并使用UserId作为用户拥有此数据的标记。使用Owin OAuth 2.0我无法使用Identity获取UserId,它返回null
。所以我想出了这个解决方案:
令牌提供程序
identity.AddClaim(new Claim("user_id", user.Id));
API
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var userName = principal.Claims.Where(c => c.Type == "user_id").Single().Value;
更简单的API代码
var userName = ClaimsPrincipal.Current.Claims.First(c => c.Type == "user_id").Value;
这种方法是否适用于企业级业务应用程序,是否安全,可靠且健壮?或者你(也许)会建议别的什么?
我只是不喜欢在Microsoft.AspNet.Identity(.NET本身)提供此功能(可能)时在令牌内传递UserId的想法,但由于我无法使其工作,这是我的现在唯一的选择。
无论如何,我部分使用来自this great tutorial repository的代码。正如您所看到的,此控制器具有注释行,这些行使用Identity来获取UserId。但这对我不起作用,所以我使用另一个使用声明的注释行。
答案 0 :(得分:4)
因为,您正在使用OWIN,我也会假设您正在使用ASP.NET身份。您不需要将用户ID存储为声明。您可以随时通过以下方式获取:
User.Identity.GetUserId()
如果Intellisense吓坏了,你只需要添加Microsoft.AspNet.Identity
命名空间。
答案 1 :(得分:0)
我假设以下代码中的身份对象的类型为 ClaimsIdentity 。你如何以及在哪里初始化这个对象?
identity.AddClaim(new Claim("user_id", user.Id));
如果查看在Visual Studio中为Web应用程序生成的默认模板,将会有一个IdentityModel类,您可以在其中查看如下所示的代码,并在登录ASP.Net Identity时调用此代码。
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
此外,它还负责添加默认声明数据,您还可以对此进行扩展以添加其他信息,例如用户phonenumber(主要是为了避免往返数据库并将其他用户信息存储为声明)。
那么你什么时候创建身份对象?
如果您有疑问是否可以添加更多信息作为声明,我想这应该没问题。
的输出是什么?identity.GetUserId();
在你的情况下?
您可以按照http://anthonychu.ca/post/aspnet-identity-20---logging-in-with-email-or-username/
中的说明进一步编写自己的IdentityExtensions类更新1 -
当您使用ASP.Net Identity系统登录时,它会调用GenerateUserIdentityAsync,它在内部调用UserClaimsPrincipalFactory类中定义的CreateAsync方法。这是代码https://github.com/aspnet/Identity/blob/daa50df87feb9f1b59858a22f00a2984996738c6/src/Microsoft.AspNet.Identity/UserClaimsPrincipalFactory.cs。如果你看一下这个方法,它实际上会做你明确做的事情
var id = new ClaimsIdentity(Options.Cookies.ApplicationCookieAuthenticationScheme, Options.ClaimsIdentity.UserNameClaimType, Options.ClaimsIdentity.RoleClaimType);
id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId)); .
所以我相信你还需要做什么