[英]Asp.net Roles Web Api check annotation "authorize" programmatically
[英]Authorize Error - ASP.NET Web API with Token based authorization and Roles
我使用Web API 2与基于OWIN令牌的身份验证。 一切顺利,除了基于角色的授权。
这是我的控制器:
[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表中的Admin。
这是我的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);
}
你能检查一下你的api方法是否解决了“Admin”声明...
var identity = User.Identity as ClaimsIdentity;
var claim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role && c.Value == "Admin");
if (claim == null) {
//Raise 401
}
Authorize属性不了解声明。 它将Admin视为角色,因此它调用IPrincipal接口的“User.IsInRole”方法。
为了完成这项工作,您需要在owin管道中将声明添加为角色并分配给HttpContext.Current.User。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.