Tuesday, 4 October 2011

Using the ASP.NET membership provider in an MVC controller

You can refer to the default ASP.NET membership provider in the controller action using the Membership.Provider object, just as in ASP.NET Web Forms. This is because ASP.NET MVC uses the same ASP.NET infrastructure as Web Forms. This is how the default AccountController, built when you select the ASP.NET MVC 3 Internet Application template, provides authentication functionality. It declares an IMembershipService interface dependency, to abstract the authentication functionality, and instantiates this with the AccountMembershipService concrete class in the controller’s Initialize method:

public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
    if (FormsService == null) { FormsService = new
    FormsAuthenticationService(); }
    if (MembershipService == null) { MembershipService = new
    AccountMembershipService(); }

    base.Initialize(requestContext);
}


The IMembershipService interface and AccountMembershipService implementation are in the AccountModels file.

Of course you can check whether the current identity is authorized without having to directly use the Membership.Provider object, by using the AuthorizeAttribute attribute.

[Authorize]
public ActionResult About()
{
    return View();
}


Adding this attribute to the action method declaration will make the MVC runtime check whether the identity is authenticated. If the identity is not authenticated, the runtime will throw a SecurityException exception.