Asp.net
使用 Web API 對屬性角色進行身份授權
我有一個小型 Web API 應用程序,它使用 Identity 來管理使用 Owin Bearer Tokens 的使用者。這個實現的基礎工作很好:我可以註冊一個使用者,登錄一個使用者並訪問標有 的 Web API 端點
[Authorize]。我的下一步是使用角色來限制 Web API 端點。例如,只有管理員角色的使用者才能訪問的控制器。我已經創建瞭如下的管理員使用者,並將它們添加到管理員角色。但是,當我從
[Authorize]to更新現有控制器[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; } }問:設置和使用角色的正確方法是什麼?
您如何在使用者登錄時為他們設置聲明我相信您在方法中缺少這行程式碼
GrantResourceOwnerCredentialsvar 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);