C# ASP身份2+;Web API令牌身份验证-未加载持久声明
我在ASP.NET Web API令牌身份验证中遇到一些问题 基本上,我创建了一个具有一些声明的用户(值存储在AspNetUserClaim表中),但是当创建用户标识时,这些声明不会从数据库中提取出来 我的设置明细如下C# ASP身份2+;Web API令牌身份验证-未加载持久声明,c#,authentication,asp.net-web-api,asp.net-identity,asp.net-identity-2,C#,Authentication,Asp.net Web Api,Asp.net Identity,Asp.net Identity 2,我在ASP.NET Web API令牌身份验证中遇到一些问题 基本上,我创建了一个具有一些声明的用户(值存储在AspNetUserClaim表中),但是当创建用户标识时,这些声明不会从数据库中提取出来 我的设置明细如下 用户类:有一个GenerateUserIdentityAsync方法(相当标准)和两个自定义属性: public class LibraryUser : IdentityUser{ //Add Custom Properties Here public strin
public class LibraryUser : IdentityUser{
//Add Custom Properties Here
public string Company { get; set; }
public string DisplayName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<LibraryUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
}
公共类库用户:IdentityUser{
//在此处添加自定义属性
公共字符串公司{get;set;}
公共字符串DisplayName{get;set;}
公共异步任务GenerateUserIdentityAsync(UserManager管理器,字符串身份验证类型)
{
//注意authenticationType必须与CookieAuthenticationOptions.authenticationType中定义的类型匹配
var userIdentity=wait manager.CreateIdentityAsync(这是authenticationType);
//在此处添加自定义用户声明
返回用户身份;
}
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Modify the Model creation properties..
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//Rename Identity 2.0 Tables to something nicer..
modelBuilder.Entity<LibraryUser>().ToTable("LibraryUser");
modelBuilder.Entity<IdentityUser>().ToTable("LibraryUser");
modelBuilder.Entity<IdentityRole>().ToTable("Role");
modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
基于模型创建(modelBuilder);
//修改模型创建属性。。
modelBuilder.Conventions.Remove();
//将Identity 2.0表重命名为更好的名称。。
modelBuilder.Entity().ToTable(“LibraryUser”);
modelBuilder.Entity().ToTable(“LibraryUser”);
modelBuilder.Entity().ToTable(“角色”);
modelBuilder.Entity().ToTable(“UserRole”);
modelBuilder.Entity().ToTable(“UserClaim”);
modelBuilder.Entity().ToTable(“UserLogin”);
}
public class LibraryUserManager : UserManager<LibraryUser>
公共类LibraryUserManager:UserManager
// -- Create Admin User, put in admin role..
LibraryUserManager userManager = new LibraryUserManager(new UserStore<LibraryUser>(context));
var user = new LibraryUser()
{
UserName = "admin@admin.com",
Email = "admin@admin.com",
DisplayName = "Administrator",
Company = "Test"
};
userManager.Create(user, "Password1.");
userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "user"));
userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "author"));
userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "reviewer"));
userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, "admin"));
/--创建管理员用户,设置为管理员角色。。
LibraryUserManager userManager=newlibraryusermanager(newuserstore(context));
var user=new LibraryUser()
{
用户名=”admin@admin.com",
电子邮件=”admin@admin.com",
DisplayName=“管理员”,
Company=“Test”
};
创建(用户“Password1”);
userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“user”);
userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“author”);
userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“审阅者”);
userManager.AddClaim(user.Id,新声明(ClaimTypes.Role,“admin”);
var userManager = context.OwinContext.GetUserManager<LibraryUserManager>();
LibraryUser user = await userManager.FindAsync(context.UserName, context.Password);
//check if a user exists
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName, user.DisplayName, oAuthIdentity);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
var userManager=context.OwinContext.GetUserManager();
LibraryUser=await userManager.FindAsync(context.UserName,context.Password);
//检查用户是否存在
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
返回;
}
ClaimsIdentity oAuthIdentity=await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
AuthenticationProperties=CreateProperties(user.UserName、user.DisplayName、oAuthIdentity);
AuthenticationTicket=新的AuthenticationTicket(OAuthidentitity,属性);
上下文。已验证(票证);
public static AuthenticationProperties CreateProperties(字符串用户名、字符串显示名、ClaimsIdentity oAuthIdentity)
{
IDictionary data=新字典
{
{“用户名”,用户名},
{“displayName”,displayName},
{“roles”,string.Join(“,”,oAuthIdentity.Claims.Where(c=>c.Type==ClaimTypes.Role)。选择(c=>c.Value.ToArray())}
};
返回新的AuthenticationProperties(数据);
}
AddClaim()
中做过)和使包含在令牌中的声明是不同的。您必须手动将索赔数据放入继承的OAuthAuthorizationServerProvider
类中,ASP.NET在Provider文件夹或您创建的任何oauth Provider中为其提供默认应用程序noauthProvider.cs
在那里,重写的GrantResourceOwnerCredentials()
方法没有AuthenticationTicket=newauthenticationTicket(oAuthIdentity,属性)代码>以便将声明放入令牌中
然后,Windows Identity将从您放置的令牌中读取声明
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var userManager = _container.GetInstance<ApplicationUserManager>())
{
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user);
// Below line adds additional claims in token.
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
public static AuthenticationProperties CreateProperties(AspNetUser user)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{"Id", user.Id.ToString(CultureInfo.InvariantCulture)},
{"http://axschema.org/namePerson", user.Nickname,},
{"http://axschema.org/contact/email", user.Email,},
};
return new AuthenticationProperties(data);
}
public override异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext)
{
使用(var userManager=\u container.GetInstance())
{
var user=await userManager.FindAsync(context.UserName,context.Password);
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
返回;
}
ClaimsIdentity oAuthIdentity=等待userManager.CreateIdentityAsync(用户,
context.Options.AuthenticationType);
ClaimSideEntity cookiesIdentity=await userManager.CreateIdentityAsyn
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (var userManager = _container.GetInstance<ApplicationUserManager>())
{
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user);
// Below line adds additional claims in token.
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
}
public static AuthenticationProperties CreateProperties(AspNetUser user)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{"Id", user.Id.ToString(CultureInfo.InvariantCulture)},
{"http://axschema.org/namePerson", user.Nickname,},
{"http://axschema.org/contact/email", user.Email,},
};
return new AuthenticationProperties(data);
}
modelBuilder.Entity<LibraryUser>().ToTable("LibraryUser");
modelBuilder.Entity<IdentityUser>().ToTable("LibraryUser"); // <-- this one