15 April, 2013
0 Comments
1 category
If you are using the SimpleMembershipProvider for FormAuthentication in a ASP .NET MVC4 / Web Api project, the following PowerShell / C# code can be used to create and delete users and roles.
- Create an empty XML App.config file "C:\Temp\App.config".
- Paste the XML below in the file and save it.
- Create an empty PowerShell file "C:\Temp\Manage_MVC_users_and_roles.ps1".
- Paste the PowerShell code below in the file and save it.
- Create an empty C# file "C:\Temp\Manage_MVC_users_and_roles.cs".
- Paste the C# code below in the file and save it.
- Execute the file "C:\Temp\Manage_MVC_users_and_roles.ps1" with PowerShell.
This will create an user "test2" with password "test2" and a role "Administrators".
Note
- Database tables will automatically be created if they don’t exist.
- De folder "C:\Temp" should contain the assemblies "System.Web.WebPages.dll" and "WebMatrix.Data.dll" and "WebMatrix.WebData.dll", this assembly can be downloaded using NuGet.
App.config
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <profile defaultProvider="SimpleProfileProvider"> <providers> <add name="SimpleProfileProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" connectionStringName="DefaultConnection" applicationName="/" /> </providers> </profile> <membership defaultProvider="SimpleMembershipProvider"> <providers> <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" /> </providers> </membership> <roleManager enabled="true" defaultProvider="SimpleRoleProvider"> <providers> <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/> </providers> </roleManager> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> </assemblyBinding> </runtime> </configuration>
PowerShell code (Manage_MVC_users_and_roles.ps1)
# Get folder containing this script. $scriptFolder = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent # Load App.config file from scriptfolder. $appConfigPath = "$scriptFolder\App.config" [System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $appConfigPath) # Compile C# code to dll. $Assem = ( "WebMatrix.Data", "WebMatrix.WebData", "System.Security", "System.Web", "System.Web.WebPages", 'System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35', 'System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ) $codePath = "$scriptFolder\Manage_MVC_users_and_roles.cs" $codeAssemblyName = "Manage_MVC_users_and_roles.dll" Add-Type -OutputType Library –ReferencedAssemblies $Assem -OutputAssembly $codeAssemblyName -Path $codePath # Load dll. $codeAssemblyPath = "$scriptFolder\$codeAssemblyName" Add-Type -Path $codeAssemblyPath # Execute C# code. $wrapper = New-Object Research.Rli.WebSecurityExecuter $wrapper.Execute($scriptFolder); pause
C# code
namespace Research.Rli { using System.Linq; public interface IWebSecurityExecuter { void Execute(string scriptFolder); } public class WebSecurityExecuter : IWebSecurityExecuter { /// <summary> /// Executes code found in the [WebSecurityWrapper] class in a new .net AppDomain, /// To prevent assembly load errors, a new AppDomain is created, with the ApplicationBase set to the folder containing this *.cs file. /// </summary> /// <param name="scriptFolder"> /// Folder containing this *.cs file. /// </param> public void Execute(string scriptFolder) { System.AppDomain childDomain = null; try { var domainSetup = new System.AppDomainSetup() { ApplicationBase = scriptFolder, ConfigurationFile = System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, ApplicationName = System.AppDomain.CurrentDomain.SetupInformation.ApplicationName, LoaderOptimization = System.LoaderOptimization.MultiDomainHost }; childDomain = System.AppDomain.CreateDomain("NewAppDomain", null, domainSetup); IWebSecurityWrapper wrapper = (IWebSecurityWrapper)childDomain.CreateInstanceAndUnwrap(typeof(WebSecurityWrapper).Assembly.FullName, typeof(WebSecurityWrapper).FullName); wrapper.Initialize(); wrapper.CreateUsers(); wrapper.CreateRoles(); } finally { if (childDomain != null) System.AppDomain.Unload(childDomain); } } } public class WebSecurityWrapper : System.MarshalByRefObject, IWebSecurityWrapper { /// <summary> /// Initializes the database connection and creates tabels, when these tables do not exist. /// </summary> public void Initialize() { DatabaseConnectionString = @"Data Source=(LocalDb)\v11.0;Initial Catalog=MyDatabase;Integrated Security=SSPI;"; Roles = new System.Collections.Generic.List<string> { "Administrators" }; Users = new System.Collections.Generic.List<User> { new User { Name = "test2", Password = "test2"} }; UserIdColumnName = "UserId"; UserNameColumnName = "UserName"; UserTableName = "UserProfile"; // Creates user and role tables if they don't exist. WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(DatabaseConnectionString, "System.Data.SqlClient", UserTableName, UserIdColumnName, UserNameColumnName, true); } public string DatabaseConnectionString { get; set; } public System.Collections.Generic.List<string> Roles { get; set; } public System.Collections.Generic.List<User> Users { get; set; } public string UserIdColumnName { get; set; } public string UserNameColumnName { get; set; } public string UserTableName { get; set; } public void CreateRoles() { Roles.ForEach(x => { var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider; if (roles.RoleExists(x)) { System.Console.WriteLine("Role [{0}] already exists.", x); } else { roles.CreateRole(x); } }); } public void CreateUsers() { Users.ForEach(x => { if (WebMatrix.WebData.WebSecurity.UserExists(x.Name)) { System.Console.WriteLine("User [{0}] already exists.", x.Name); } else { WebMatrix.WebData.WebSecurity.CreateUserAndAccount(x.Name, x.Password); } }); } public void DeleteRoles() { Roles.ForEach(x => { var roles = (WebMatrix.WebData.SimpleRoleProvider)System.Web.Security.Roles.Provider; if (roles.RoleExists(x)) { System.Collections.Generic.List<string> usersInRole = roles.GetUsersInRole(x).ToList(); Users = new System.Collections.Generic.List<User>(); usersInRole.ForEach(u => { Users.Add(new User { Name = u }); }); DeleteUsers(); roles.DeleteRole(x, true); } else { System.Console.WriteLine("Role [{0}] already exists.", x); } }); } public void DeleteUsers() { var membership = (WebMatrix.WebData.SimpleMembershipProvider)System.Web.Security.Membership.Provider; Users.ForEach(x => { if (WebMatrix.WebData.WebSecurity.UserExists(x.Name)) { membership.DeleteAccount(x.Name); membership.DeleteUser(x.Name, true); } else { System.Console.WriteLine("User [{0}] does not exist.", x.Name); } }); } public void ResetPasswordUsers() { Users.ForEach(x => { if (WebMatrix.WebData.WebSecurity.UserExists(x.Name)) { WebMatrix.WebData.WebSecurity.ResetPassword(null, x.Name); } else { System.Console.WriteLine("User [{0}] does not exist.", x.Name); } }); } } public interface IWebSecurityWrapper { void CreateRoles(); void CreateUsers(); string DatabaseConnectionString { get; set; } void DeleteRoles(); void DeleteUsers(); void Initialize(); void ResetPasswordUsers(); System.Collections.Generic.List<string> Roles { get; set; } string UserIdColumnName { get; set; } string UserNameColumnName { get; set; } System.Collections.Generic.List<Research.Rli.User> Users { get; set; } string UserTableName { get; set; } } public class User { public string Name { get; set; } public string Password { get; set; } } }
Category: Uncategorized