【发布时间】:2015-01-06 18:06:51
【问题描述】:
我在我的 WebAPI 控制器操作中使用 [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;
}
}
在Global.asax.csApplication_Start注册
GlobalConfiguration.Configuration.MessageHandlers.Add(new MyProject.AuthenticationHandler1());
它一直显示这个消息
{"Message":"Authorization has been denied for this request."}
【问题讨论】:
-
我的内置 Authorize 属性也有同样的问题,我不应该创建自定义属性
标签: asp.net asp.net-mvc asp.net-web-api authorize-attribute