pr0g33k

SimpleMembershipProvider Error When Restarting Application After Authentication

If you're using the SimpleMembershipProvider in MVC4 and using the MVC template that includes the InitializeSimpleMembershipAttribute class in the Filters directory, you might have come across an issue when you restart your application after logging in. The error that's thrown states that, “You must call the 'WebSecurity.InitializeDatabaseConnection' method before you call any other method of the 'WebSecurity' class. It appears that the filter does not initialize the database connection early enough in the lifecycle to be picked up by the SimpleRoleProvider. For example, this will occur if you have methods decorated with the [Authorize] attribute and you're limiting access to a particular set of roles (e.g. [Authorize(Roles = "Administrator")]). Attempting to access the roles provider in this case causes the error to occur if the application is restarted (e.g. as a result of making a change to the Web.Config or a recompile).

The solution is to move the initialization to Application_Start(). In keeping with the existing code in Application_Start(), I added a new class in the App_Start directory called "WebSecurityConfig"

public class WebSecurityConfig
{
    public static void Initialize()
    {
        Database.SetInitializer<UsersContext>(null);

        try
        {
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("The database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
        }
    }
}
    

Then, in Application_Start(), add: WebSecurityConfig.Initialize();

Delete the InitializeSimpleMembershipAttribute from your project as well as any [InitializeSimpleMembership] attributes on your controller methods.

Posted on 6/5/2013 at 07:06 PM
Tags: MVCC#

Comments:

Leave a comment
  1. CAPTCHA