我正在尝试实施密码到期策略,并找到了一个很好的博客,展示了一个示例 - 但那是在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);
}
在 WebAPI 上,覆盖方法签名是
OnAuthorization(HttpActionContext actionContext)
而不是(AuthorizationContext filterContext)
- 如何使用 actionContext 检查SkipPasswordExpirationAttribute
?一旦我确定密码已过期,我应该采取什么措施?我不认为我可以从 WebApi "重定向"用户,因为这没有任何意义。
使用 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);
}