我有一个小型的Web应用程序,它使用标识来管理使用Owin令牌的用户。这个实现的基本原理很好:我可以注册一个用户,登录一个用户,并访问使用[Authorize]标记的Web端点。
我的下一步是使用角色限制Web端点。例如,只有管理员角色中的用户才能访问的控制器。我如下所示创建了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;
}
}问:设置和使用角色的正确方法是什么?
发布于 2014-10-27 14:23:54
当用户登录时,您是如何设置声明的?我相信您在方法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);https://stackoverflow.com/questions/26581513
复制相似问题