我在 WebAPI Controller 操作上使用 [Authorize]
属性,但它总是未经授权返回。
这是我的行动
[Authorize(Roles = "Admin")]
public IQueryable<Country> GetCountries()
{
return db.Countries;
}
这是我在全局消息处理程序中设置授权的位置。这是为了测试,我放入了一个测试用户。
public class AuthenticationHandler1 : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.User = TestClaimsPrincipal();
}
return base.SendAsync(request, cancellationToken);
}
private ClaimsPrincipal TestClaimsPrincipal()
{
var identity = new ClaimsIdentity(HttpContext.Current.User.Identity.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, "some.user"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor"));
var testIdentity = new ClaimsIdentity(identity);
var myPrincipal = new ClaimsPrincipal(testIdentity);
return myPrincipal;
}
}
在 Application_Start
中的 Global.asax.cs
中注册
GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());
它一直显示一条消息
{"Message":"Authorization has been denied for this request."}
最佳答案
我创建了一个自定义授权属性并且它有效。
public class AuthorizationAttribute : System.Web.Http.AuthorizeAttribute
{
public string Roles { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
ClaimsPrincipal currentPrincipal = HttpContext.Current.User as ClaimsPrincipal;
if (currentPrincipal != null && CheckRoles(currentPrincipal))
{
return true;
}
else
{
actionContext.Response =
new HttpResponseMessage(
System.Net.HttpStatusCode.Unauthorized)
{
ReasonPhrase = "Some message"
};
return false;
}
}
private bool CheckRoles(ClaimsPrincipal principal)
{
string[] roles = RolesSplit;
if (roles.Length == 0) return true;
return roles.Any(principal.IsInRole);
}
protected string[] RolesSplit
{
get { return SplitStrings(Roles); }
}
protected static string[] SplitStrings(string input)
{
if(string.IsNullOrWhiteSpace(input)) return new string[0];
var result = input.Split(',').Where(s=>!String.IsNullOrWhiteSpace(s.Trim()));
return result.Select(s => s.Trim()).ToArray();
}
}
像这样使用
[AuthorizationAttribute(Roles = "SomeRole,Admin")]
public IQueryable<Country> GetCountries()
{
}
关于asp.net - Web API 授权属性不适用于操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27804506/