【问题标题】:How to implement AuthorizationContext attribute on WebApi?如何在 Web Api 中实现 Authorization Context 属性?
【发布时间】:2017-08-24 18:06:40
【问题描述】:

我正在尝试实施密码过期策略并找到了一个好的blog showing an example - 但那是在 MVC 中。我正在尝试为 WebApi2 实现它。我希望 WebApi 具有类似的功能,但到目前为止未能找到要调用的正确命名空间/方法。

相关部分代码:

public override void OnAuthorization(AuthorizationContext filterContext)
{
    if (!filterContext.ActionDescriptor.IsDefined(typeof(SkipPasswordExpirationCheckAttribute), inherit: true)
        && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SkipPasswordExpirationCheckAttribute), inherit: true))
        {
            ...

            if (timeSpan.Days >= _maxPasswordAgeInDay)
            {
                ...

                filterContext.HttpContext.Response.Redirect(urlHelper.Action("ChangePassword", "Account", new { reason = "passwordExpired" }));
            }
        }

    base.OnAuthorization(filterContext);
}
  1. 在 WebApi 上,覆盖方法签名是 OnAuthorization(HttpActionContext actionContext) 而不是 (AuthorizationContext filterContext) - 如何使用 actionContext 检查 SkipPasswordExpirationAttribute?

  2. 一旦我确定密码已过期,我应该采取什么措施?我不认为我可以从 WebApi “重定向”用户,因为这没有任何意义。

【问题讨论】:

    标签: c# asp.net-web-api asp.net-identity


    【解决方案1】:

    使用ActionDescriptor 或ControllerContext 属性查找所需的属性。

    这是一个如何检查SkipPasswordExpirationAttribute 的示例。

    public override void OnAuthorization(HttpActionContext actionContext) {
        var attribute = actionContext.ActionDescriptor.GetCustomAttributes<SkipPasswordExpirationAttribute >(true).FirstOrDefault();
        if (attribute != null)
            return;
        //You have access to the Request and Response as well.
        var request = actionContext.Request;
        var response = actionContext.Response;
    
        //...Once you decide the password has expired, 
        //update the response with an appropriate status code 
        //and response message that would make sense 
        //to the client that made the request
        response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
        response.ReasonPhrase = "Password expired";
    
        base.OnAuthorization(actionContext);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 2023-02-21
      相关资源
      最近更新 更多