【问题标题】:Custom Authorization in Asp.net WebApi call only for authorize attributeAsp.net WebApi 中的自定义授权仅针对授权属性调用
【发布时间】: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


    【解决方案1】:

    我自己找到了答案。

    如果将过滤器添加到全局 asax,那么它将被所有 控制器和操作,无论是否提及。

    所以我们需要从 global.asax

    中删除以下内容
    GlobalConfiguration.Configuration.Filters.Add(new CustomAuthorize());
    

    所以现在,只有在控制器或动作中提及时才会调用自定义的 athorize。

    【讨论】:

      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2014-10-28
      • 2021-01-12
      相关资源
      最近更新 更多