【发布时间】:2017-04-05 22:59:35
【问题描述】:
我已经实现了基于令牌的身份验证。 我想编写自定义授权属性。
这背后的原因是,有时 UserIdentity.GetUserId() 会给出 null。
为了解决这个问题,我编写了自定义授权属性,如下所示。
此自定义 Authorize 调用所有调用(匿名或授权调用)。 所以我使用了 IsAuthorizeCall 属性来检查调用是来自匿名还是授权。
我可以打电话吗,我只想在我提到上述方法时调用这个自定义授权。否则不应调用它。
我该怎么做?
public class CustomAuthorize : AuthorizationFilterAttribute
{
public bool IsAuthorizeCall { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (IsAuthorizeCall)
{
IdentityHelper IdentityHelper = new IdentityHelper();
if (IdentityHelper.UserId== Guid.Empty)
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
参考:
Custom Authorization in Asp.net WebApi - what a mess?
How to Customize ASP.NET Web API AuthorizeAttribute for Unusual Requirements
【问题讨论】:
标签: asp.net-mvc asp.net-web-api