我正在尝试实施密码到期策略并找到一个好的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);
}
在WebApi上,覆盖方法签名为OnAuthorization(HttpActionContext actionContext)
而不是(AuthorizationContext filterContext)
- 如何使用actionContext检查SkipPasswordExpirationAttribute
?
一旦我确定密码已过期,我应该采取什么行动?我不认为我可以从WebApi“重定向”用户,因为这没有任何意义。
答案 0 :(得分:2)
使用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);
}