Question

I need to verify whether the authenticated user has an active membership to my site. For example, if the user's membership is active they are freely able to browse the "members only" area of the site, whereas if their membership is inactive or expired they are automatically redirected to the billing area of the website. They would only be able to view certain restricted pages.

I am thinking of approaching this by storing the user's membership expiration date in the FormsAuthentication cookie. I am using a custom MembershipProvider and already storing the user's ID in the cookie, so this would be easy to do. The authentication cookie is set to expire in 24 hours. Then I would check whether their membership is active using a custom AuthorizeAttribute, like so:

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);
    }
}

Then I can just decorate my controllers as such:

[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
}

Is this a good approach to take or is there a cleaner/more preferable method to validate whether a user's membership is active? I would prefer not having to hit the database on every request just to retrieve the user's membership expiration date or status, which is why I want to store this value in a cookie. Also, is it fine to store this value in the FormsAuthentication cookie, or should I be storing this in a different cookie?

Was it helpful?

Solution

Storing that information in a cookie does not strike me as the right approach. The reason, as it is pointed out in this answer https://stackoverflow.com/a/706874/2168278 is that cookies are stored in the client's machine. So it's possible that they can be tampered.

Storing this information in a database seems more appropriate. If you are concerned about performance you can always cache your queries.

OTHER TIPS

I would approach this differently. I would have a background process to check for memberships that are expiring and disable those accounts.

If users attempt to login I would check if the account is disabled and then act upon that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top