1
我正在使用基于OWIN令牌的Web API 2验证。除了基于角色的授权之外,一切进展顺利。授权错误 - 基于令牌的授权和角色的ASP.NET Web API
这里是我的控制器:
[Authorize(Roles = "Admin")]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
..............
// POST api/Account/Register
//[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(AppUser user)
{
...............
的问题如下:我登录我的应用程序与具有角色admin用户,但我得到授权错误401尝试注册时。我已经纠正了我用来登录的AspNetUser是AspNetUserRoles表中的管理员。
这里是我的GrantResourceOwnerCredentials方法:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository(new GloboStudioUniversityContext()))
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
//identity.AddClaim(new Claim("role", "user"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Student"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Candidate"));
context.Validated(identity);
}
为了调试的目的,您可以删除Authorize属性,然后在方法中调用User.IsInRole(“Admin”)'并且遍历所有声明以查看用户是否真的是Admin组的一部分。 – Michael
我已经调试过,IsInRole说我的用户不属于管理员组。有什么可能错误或失踪? –