我在 MVC 3 站点中使用表单身份验证和 ASP 通用成员资格提供程序。 为了方便用户,我们保留了 Cookie。
FormsAuthentication.SetAuthCookie(model.UserName, true)
当我们像这样禁用成员资格提供程序中的用户时:
memUser.IsApproved = model.IsActive;
provider.UpdateUser(memUser);
如果他们有cookie,他们仍然可以进入该网站。 这类似于这篇文章中描述的内容:http://stackoverflow.com/questions/5825273/how-do-you-cancel-somes-persistent-cookie-if-their-member-is-no-longer-v
我们在控制器上使用授权属性,我知道这在技术上比身份验证更授权。 但是肯定是溢出,所以我试图找出检查用户实际上没有被禁用的最佳 MVC 方法是什么? 自定义授权属性,根据成员资格数据库检查用户? 我缺少一个明显的设置/方法,表单身份验证使票证无效?
更新:
这基本上是我要做的 - 我们使用自定义权限拒绝页面,我们用它来更好地通知用户他们没有权限而不是他们没有登录。 我添加了已批准的支票。 当您将属性放在控制器或操作上时,将调用 AuthorizeCore,如果它返回假 HandleUnauthorizedRequest。
public class CustomAuthorization : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated || !Membership.GetUser(filterContext.HttpContext.User.Identity.Name).IsApproved)
{
filterContext.Result = new HttpUnauthorizedResult();
// in the case that the user was authenticated, meaning he has a ticket,
// but is no longer approved we need to sign him out
FormsAuthentication.SignOut();
}
else
{
var permDeniedRouteVals = new System.Web.Routing.RouteValueDictionary() { { "controller", "MyErrorController" }, { "action", "MyPermissionDeniedAction" }, { "area", null } };
filterContext.Result = new RedirectToRouteResult(permDeniedRouteVals);
}
}
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
// since persisting ticket,
// adding this check for the case that the user is not active in the database any more
return base.AuthorizeCore(httpContext) && Membership.GetUser(httpContext.User.Identity.Name).IsApproved;
}
}
用法:
[CustomAuthorization()]
public class MyController
好吧,无论如何,您都必须检查数据库,唯一的问题是您要如何做到这一点。 是的,您可以创建自定义授权属性,也可以在 ControllerBase 中为 OnAuthorize 覆盖编写一些代码,也可以在 Application_AuthenticateRequest 中执行此操作。你可以用很多方法做到这一点,这取决于什么最适合你。
当然,最好的方法是,如果这对您来说是一个问题,请不要使用持久票证。
我几乎总是使用角色和角色提供程序,即使只有一个名为"登录"的角色 - 部分原因是这个问题。这样,您的Authorize
属性可能如下所示:
[Authorize(Roles="Login")]
其中Login
代表一个基本的"角色",所有"活动"帐户都必须能够登录;每个受保护的操作至少都受此保护。
这样,只需删除"登录"角色即可有效地禁用用户...因为,在我的角色提供程序中,我正在根据数据库或服务器本地等效项检查登录用户的角色。
在您的情况下,您的"登录"角色可以简单地解析为检查用户模型上的IsApproved
字段。