我在我的WebAPI控制器操作上使用[Authorize]
属性,并且它总是未经授权回来。
这是我的行动
[Authorize(Roles = "Admin")]
public IQueryable<Country> GetCountries()
{
return db.Countries;
}
以下是我在Global MessageHandler中设置授权的地方。这是为了测试我投入测试用户。
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;
}
}
在Global.asax.cs
Application_Start
注册
GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());
它会一直显示此消息
{"Message":"Authorization has been denied for this request."}
答案 0 :(得分:2)
我制作了自定义授权属性,但它确实有效。
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()
{
}