您需要一个特殊的身份验证全局操作过滤器。
您的问题的解决方案如下。您必须引入将在调用控制器操作之前执行的全局操作过滤器。这个事件被命名为OnActionExecuting
。在这个全局操作过滤器中,您还可以处理用户具有有效身份验证 cookie,但不再存在于持久性 (DB) 中的场景(并且您必须删除其 cookie)。
这是获取想法的代码示例:
public class LoadCustomPrincipalAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
CustomIdentity customIdentity;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
UserData userData = UserRepository.GetUserByName(HttpContext.Current.User.Identity.Name);
if (userData == null)
{
//TODO: Add here user missing logic,
//throw an exception, override with the custom identity with "false" -
//this boolean means that it have IsAuthenticated on false, but you
//have to override this in CustomIdentity!
//Of course - at this point you also remove the user cookie from response!
}
customIdentity = new CustomIdentity(userData, true);
}
else
{
customIdentity = new CustomIdentity(new UserData {Username = "Anonymous"}, false);
}
HttpContext.Current.User = new CustomPrincipal(customIdentity);
base.OnActionExecuting(filterContext);
}
}
希望对你有帮助!
不要忘记将此操作过滤器注册为全局过滤器。你可以这样做:
private static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LoadCustomPrincipalAttribute());
}
只是为了添加这个。别管了AuthorizeAttribute
。它应该按预期工作。它只是检查HttpContext.Current.User.Identity.IsAuthenticated == true
条件。在某些情况下,您需要覆盖它,但这不是一个。在开始之前,您确实需要适当的用户/身份验证处理AuthorizeAttribute
。