Assigning Roles with MVC SimpleMembership
Solution 1
You need to use the Roles API to interact with the Roles. Something like the following should work:
if (!Roles.RoleExists("Administrator"))
Roles.CreateRole("Administrator");
if (!Roles.GetRolesForUser(model.UserName).Contains("Administrator"))
Roles.AddUsersToRole(new[] { model.UserName }, "Administrator");
Solution 2
WebSecurity.InitializeDatabaseFile("SecurityDemo.sdf", "Users", "UserID", "Username", true);
CHeck out this website. It may be of some help. http://blog.osbornm.com/archive/2010/07/21/using-simplemembership-with-asp.net-webpages.aspx
JustAnotherDeveloper
Developer and Geek who knows way too many pointless facts and not enough code...
Updated on June 03, 2022Comments
-
JustAnotherDeveloper almost 2 years
I am trying out "SimpleMembership" in MVC3 via Nuget and have downloaded the sample to play with. The issue is that I cannot figure out how I would assign a role to a particular user.
In the standard MVC membership you can just use something like:
Roles.AddUserToRole(model.UserName, "StandardUser");
However, SimpleMembership only seems to have one method for roles exposed (unless Im being stupid!) which is
public void RequireRoles(params string[] roles) { WebSecurity.RequireRoles(roles); }
There must be an easy way as the following table was created as part of this nuget package:
-TABLE: webpages_Roles RoleId , RoleName
This is slightly confusing though as in
App_Start/SimpleMembershipMvc3.cs
there is the following:Roles.Enabled = true; RoleProvider provider3 = Roles.Providers["AspNetSqlRoleProvider"]; if (provider3 != null) { RoleProvider provider6 = provider3; SimpleRoleProvider provider4 = CreateDefaultSimpleRoleProvider("AspNetSqlRoleProvider", provider6); Roles.Providers.Remove("AspNetSqlRoleProvider"); Roles.Providers.Add(provider4); }
SimpleRoleProvider function
private static SimpleRoleProvider CreateDefaultSimpleRoleProvider(string name, RoleProvider currentDefault) { RoleProvider previousProvider = currentDefault; SimpleRoleProvider provider = new SimpleRoleProvider(previousProvider); NameValueCollection config = new NameValueCollection(); provider.Initialize(name, config); return provider; }
Does this package use the built in Role provider? If so, how does it hook up with the tables created by SimpleMembership