Lotok
Lotok

Reputation: 4607

Moving Security Concerns to Data Access Layer

I am moving all of the Authentication and Security concerns into my Data Access Layer on an ASP.NET MVC4 Internet Application. Everything is fine for logging in, logging out, creating users etc but I am hitting a stumbling block with adding users to roles.

After Creating a user account I want to add them to some default roles. The method for doing so looks like this

public static string CreateUserAccount(string username, string password)
{
    WebSecurity.CreateUserAndAccount(username, password);
    var roleProvider = new SimpleRoleProvider();
    roleProvider.AddUsersToRoles(new[] {username}, new[] {"MeterInfo", "SiteInfo", "AMRInfo", "InstallImages"});
    return username + " Account Created";
}

The call to WebSecurity for creating the account is OK, but my use of SimpleRoleProvider causes this error

You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class. This call should be placed in an _AppStart.cshtml file in the root of your site.

The InitializeDatabaseConnection is already handled in the AuthConfig which is called on startup by global.asax.

AssetRegisterDataLayer.DataAccess.Security.InitializeSecurity();

The method being called on my DataAccess layer looks like this

public static void InitializeSecurity()
{
    WebSecurity.InitializeDatabaseConnection("AssetRegisterDb","UserProfile","UserId","UserName", false);   
}

I have seen this issue happen when people use the out of the box config for MVC4 where the Accounts controller is decorated with the [InitializeSimpleMembership] attribute instead of calling the WebSecurity initializer at application start, but that is not the case here. Anyone know why all the WebSecurity works except roles?

Thanks very much

Upvotes: 3

Views: 347

Answers (1)

Lotok
Lotok

Reputation: 4607

I have found my mistake, I will answer my own question in case someone else has a similar issue.

The error in the code shown in my question was instantiating a new SimpleRoleProvider. I should have done this

public static string CreateUserAccount(string username, string password)
{
    WebSecurity.CreateUserAndAccount(username, password);
    var roleProvider = (SimpleRoleProvider)Roles.Provider;
    roleProvider.AddUsersToRoles(new[] {username}, new[] {"MeterInfo", "SiteInfo", "AMRInfo", "InstallImages"});
    return username + " Account Created";
}

Upvotes: 1

Related Questions