我有一个小型Web API应用程序,它使用Identity来管理使用Owin Bearer Tokens的用户.此实现的基础工作正常:我可以注册用户,登录用户并访问标有[授权]的Web API端点.
我的下一步是使用角色限制Web API端点.例如,只有Admin角色的用户才能访问的控制器.我已经创建了Admin用户,如下所示,我将它们添加到Admin角色.但是,当我将现有的控制器从[授权]更新为[授权(角色=“管理员”)]并尝试使用Adim帐户访问它时,我获得了401未授权.
//Seed on Startup public static void Seed() { var user = await userManager.FindAsync("Admin","123456"); if (user == null) { IdentityUser user = new IdentityUser { UserName = "Admin" }; var createResult = await userManager.CreateAsync(user,"123456"); if (!roleManager.RoleExists("Admin")) var createRoleResult = roleManager.Create(new IdentityRole("Admin")); user = await userManager.FindAsync("Admin","123456"); var addRoleResult = await userManager.AddToRoleAsync(user.Id,"Admin"); } } //Works [Authorize] public class TestController : ApiController { // GET api/<controller> public bool Get() { return true; } } //Doesn't work [Authorize(Roles = "Admin")] public class TestController : ApiController { // GET api/<controller> public bool Get() { return true; } }
问:设置和使用角色的正确方法是什么?
解决方法
如何在用户登录时为其设置声明我相信您在方法GrantResourceOwnerCredentials中缺少这行代码
var identity = new ClaimsIdentity(context.Options.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name,context.UserName)); identity.AddClaim(new Claim(ClaimTypes.Role,"Admin")); identity.AddClaim(new Claim(ClaimTypes.Role,"Supervisor"));
如果要从DB创建标识,请使用以下内容:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> 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; }
然后在GrantResourceOwnerCredentials中执行以下操作:
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);