在.NET MVC中实现活动成员资格的验证

时间:2013-09-27 02:19:02

标签: asp.net-mvc asp.net-mvc-4 membership-provider

我需要验证经过身份验证的用户是否拥有我网站的有效成员资格。例如,如果用户的会员资格是活动的,他们可以自由地浏览网站的“仅会员”区域,而如果他们的会员资格不活动或过期,他们会自动重定向到网站的计费区域。他们只能查看某些受限制的页面。

我正在考虑通过在FormsAuthentication cookie中存储用户的成员资格到期日来解决这个问题。我使用自定义MembershipProvider并已将用户的ID存储在cookie中,因此这很容易做到。身份验证Cookie设置为24小时后过期。然后我会使用自定义AuthorizeAttribute检查其成员资格是否有效,如下所示:

public class MembershipAuthorizeAttribute : AuthorizeAttribute
{
    private readonly bool authorizeMembership;

    public MembershipAuthorizeAttribute()
    {
        this.authorizeMembership = true;
    }

    public MembershipAuthorizeAttribute(bool authorizeMembership)
    {
        this.authorizeMembership = authorizeMembership;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (this.authorizeMembership)
        {
            // Code to validate the membership hasn't expired
        }

        return base.AuthorizeCore(httpContext);
    }
}

然后我可以装饰我的控制器:

[MembershipAuthorize]
public class ActiveMembersController : Controller
{
    // Only users with an active membership can access this controller
}

[MembershipAuthorize(false)]
public class BillingController : Controller
{
   // All members can access this controller
}

这是一个很好的方法,还是有更清洁/更优选的方法来验证用户的会员资格是否有效?我希望不必在每个请求上访问数据库只是为了检索用户的成员资格到期日期或状态,这就是我想将此值存储在cookie中的原因。此外,可以将此值存储在FormsAuthentication cookie中,还是应该将其存储在另一个cookie中?

2 个答案:

答案 0 :(得分:0)

将该信息存储在cookie中并不会使我成为正确的方法。正如在这个答案https://stackoverflow.com/a/706874/2168278中指出的那样,原因是cookie存储在客户端的机器中。所以它们可能会被篡改。

将此信息存储在数据库中似乎更合适。如果您担心性能问题,可以随时缓存查询。

答案 1 :(得分:0)

我会采用不同的方法。我会有一个后台流程来检查即将到期的会员资格并禁用这些帐户。

如果用户尝试登录,我会检查该帐户是否已被禁用,然后对此采取行动。