我有一个小型Web API应用程序,它使用Identity来管理使用Owin Bearer Tokens的用户。此实现的基础工作正常:我可以注册用户,登录用户并访问标有[Authorize]
的Web API端点。
我的下一步是使用角色限制Web API端点。例如,只有Admin角色的用户才能访问的控制器。我已经创建了Admin用户,如下所示,我将它们添加到Admin角色。但是,当我将现有控制器从[Authorize]
更新为[Authorize(Roles = "Admin")]
并尝试使用Adim帐户访问它时,我得到401 Unauthorized
。
//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;
}
}
问:设置和使用角色的正确方法是什么?
答案 0 :(得分:10)
如何为用户登录时设置声明我相信您在方法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);