【发布时间】:2016-11-18 18:56:00
【问题描述】:
我正在使用基于 OWIN 令牌的身份验证的 Web API 2。除了基于角色的授权之外,一切都很顺利。
这是我的控制器:
[Authorize(Roles = "Admin")]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
..............
// POST api/Account/Register
//[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(AppUser user)
{
...............
问题如下:我使用具有管理员角色的用户登录我的应用程序,但在尝试注册时收到未经授权的错误 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);
}
【问题讨论】:
-
-
我已经调试过了,IsInRole 说我的用户不属于管理员组。有什么错误或遗漏的?
标签: c# asp.net asp.net-web-api token owin