Administer asp.net website (create new users, assign users to roles, etc.) from a windows app
Tag : chash , By : Ryan Adriano
Date : March 29 2020, 07:55 AM
around this issue I've come up with a solution, based on the other answers (who both got +1), and some other sites out there. First, I created Application Config file (app.config). It mirrors exactly what is found in web.config from the web app, with the exception of how the connection string was handled: <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="MyConnectionString"
connectionString ="SERVER=abc;UID=def;PWD=hij;Initial Catalog=klm;MultipleActiveResultsets=True"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MySqlMembershipProvider">
<providers>
<add name="MySqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MyConnectionString"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/MyWebApp"
requiresUniqueEmail="true"
passwordFormat="Encrypted"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MySqlRoleManager">
<providers>
<add name="MySqlRoleManager"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyConnectionString"
applicationName="/MyWebApp" />
</providers>
</roleManager>
<machineKey
validationKey="BC50A82A6AF6A015C34C7946D29B817C00F04D2AB10BC2128D1E2433D0E365E426E57337CECAE9A0681A2C736B9779B42F75D60F09F142C60E9E0E8F9840DB46"
decryptionKey="122035576C5476DCD8F3611954C837CDA5FE33BCDBBF23F7"
validation="SHA1"
decryption="AES"/>
</system.web>
</configuration>
using System.Configuration;
using System.Reflection;
using System.Web.Security;
namespace WebAdminViaWindows
{
internal static class Provider
{
private static readonly string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
static Provider()
{
Membership = CreateMembershipProvider();
Role = CreateRoleProvider();
}
public static MembershipProvider Membership { get; private set; }
public static RoleProvider Role { get; private set; }
private static MembershipProvider CreateMembershipProvider()
{
var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);
var systemWebGroup = config.SectionGroups["system.web"];
if (systemWebGroup == null)
{
throw new ConfigurationErrorsException("system.web group not found in configuration");
}
var membershipSection = systemWebGroup.Sections["membership"];
if (membershipSection == null)
{
throw new ConfigurationErrorsException("membership section not found in system.web group");
}
var defaultProviderProperty = membershipSection.ElementInformation.Properties["defaultProvider"];
if (defaultProviderProperty == null)
{
throw new ConfigurationErrorsException("defaultProvider property not found in membership section");
}
var defaultProviderName = defaultProviderProperty.Value as string;
if (defaultProviderName == null)
{
throw new ConfigurationErrorsException("defaultProvider property is not a string value");
}
var providersProperty = membershipSection.ElementInformation.Properties["providers"];
if (providersProperty == null)
{
throw new ConfigurationErrorsException("providers property not found in membership section");
}
var providerCollection = providersProperty.Value as ProviderSettingsCollection;
if (providerCollection == null)
{
throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
}
ProviderSettings membershipProviderSettings = null;
foreach (ProviderSettings providerSetting in providerCollection)
{
if (providerSetting.Name == defaultProviderName)
{
membershipProviderSettings = providerSetting;
}
}
if (membershipProviderSettings == null)
{
if (providerCollection.Count > 0)
{
membershipProviderSettings = providerCollection[0];
}
else
{
throw new ConfigurationErrorsException("No providers found in configuration");
}
}
var provider = new SqlMembershipProvider();
provider.Initialize("MySqlMembershipProvider", membershipProviderSettings.Parameters);
return provider;
}
private static RoleProvider CreateRoleProvider()
{
var config = ConfigurationManager.OpenExeConfiguration(assemblyFilePath);
var systemWebGroup = config.SectionGroups["system.web"];
if (systemWebGroup == null)
{
throw new ConfigurationErrorsException("system.web group not found in configuration");
}
var roleManagerSection = systemWebGroup.Sections["roleManager"];
if (roleManagerSection == null)
{
throw new ConfigurationErrorsException("roleManager section not found in system.web group");
}
var defaultProviderProperty = roleManagerSection.ElementInformation.Properties["defaultProvider"];
if (defaultProviderProperty == null)
{
throw new ConfigurationErrorsException("defaultProvider property not found in roleManager section");
}
var defaultProviderName = defaultProviderProperty.Value as string;
if (defaultProviderName == null)
{
throw new ConfigurationErrorsException("defaultProvider property is not a string value");
}
var providersProperty = roleManagerSection.ElementInformation.Properties["providers"];
if (providersProperty == null)
{
throw new ConfigurationErrorsException("providers property not found in roleManagerSection section");
}
var providerCollection = providersProperty.Value as ProviderSettingsCollection;
if (providerCollection == null)
{
throw new ConfigurationErrorsException("providers property is not an instance of ProviderSettingsCollection");
}
ProviderSettings roleProviderSettings = null;
foreach (ProviderSettings providerSetting in providerCollection)
{
if (providerSetting.Name == defaultProviderName)
{
roleProviderSettings = providerSetting;
}
}
if (roleProviderSettings == null)
{
if (providerCollection.Count > 0)
{
roleProviderSettings = providerCollection[0];
}
else
{
throw new ConfigurationErrorsException("No providers found in configuration");
}
}
var provider = new SqlRoleProvider();
provider.Initialize("MySqlRoleManager", roleProviderSettings.Parameters);
return provider;
}
}
}
int total;
foreach (MembershipUser user in Provider.Membership.GetAllUsers(0, 10, out total))
{
var sb = new StringBuilder();
sb.AppendLine(user.UserName);
foreach (var role in Provider.Role.GetRolesForUser(user.UserName))
{
sb.AppendLine("\t" + role);
}
Console.WriteLine(sb.ToString());
}
|
Get all roles under current users role
Date : March 29 2020, 07:55 AM
this will help Unfortunately, there does not appear to be a pre-built way to do this. However, you should be able to write code to do it recursively like so: public static set<Id> getSubordinateRoles(Id roleId) {
map<Id, set<Id>> parentAndChildren = new map<Id, set<Id>>();
set<Id> children;
for(UserRole ur : [select Id, ParentRoleId from UserRole]) {
children = parentAndChildren.containsKey(ur.ParentRoleId) ? parentAndChildren.get(ur.ParentRoleId) : new set<Id>();
children.add(ur.Id);
parentAndChildren.put(ur.ParentRoleId, children);
}
return getSubordinateRoles(role, parentAndChildren);
}
public static set<Id> getSubordinateRoles(Id roleId, map<Id, set<Id>> parentAndChildren) {
set<Id> subordinateRoles = new set<Id>();
set<Id> remainingSubordinateRoles = new set<Id>();
if(parentAndChildren.containsKey(roleId)) {
subordinateRoles.addAll(parentAndChildren.get(roleId));
for(Id subRoleId : subordinateRoles) {
remainingSubordinateRoles.addAll(getSubordinateRoles(subRoleId, parentAndChildren));
}
}
subordinateRoles.addAll(remainingSubordinateRoles);
return subordinateRoles;
}
|
Create login with groups (with roles) and users with revoke roles - Symfony2
Date : March 29 2020, 07:55 AM
this one helps. is_granted() calls the user's getRoles() method and checks wether the given argument role is inside the returned array of roles. ( simplified - the security provider calls getRoles and adds them to the security-context then is_granted checks the security-context to be more precise ) Now if you want to return the roles inherited from the user's groups you will have to merge those. public function getRoles()
{
$groupRoles = array();
// add all roles provided by groups
foreach ($this->getGroups() as $group) {
foreach ($group->getRoles() as $role) {
$groupRoles[] = $role;
}
}
// - remove dublicates
// - revoke user's roles
// - return remaining roles
return array_unique(array_diff($groupRoles, $this->getRoles()));
}
|
How to create roles and add users to roles in ASP.NET MVC Web API
Date : March 29 2020, 07:55 AM
it fixes the issue I have a .NET Web API project that users the individual accounts. I can register users fine using the standard template AccountController. However, I now want to set up roles and add users to roles depending on the type of user. , You can add roles using the RoleManager... using (var context = new ApplicationDbContext())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
await roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "admin" };
await userManager.CreateAsync(user);
await userManager.AddToRoleAsync(user.Id, "Administrator");
}
|
.net MVC add roles and add users and add roles to users + make part of a view only visible for a role
Date : March 29 2020, 07:55 AM
I wish this help you MVC5 project template doesn't have role manager by default, so we start by creating our role manager classes; (in order to keep the project well structured it is better to add the classes as mentioned below): 1- create ApplicationRole class (add to IdentityModels.cs under Models folder) public class ApplicationRole : IdentityRole
{
public ApplicationRole() : base() { }
public ApplicationRole(string name) : base(name) { }
}
public class ApplicationRoleManager : RoleManager<ApplicationRole>, IDisposable
{
public ApplicationRoleManager(RoleStore<ApplicationRole> store) : base(store) { }
public static ApplicationRoleManager Create(
IdentityFactoryOptions<ApplicationRoleManager> options,
IOwinContext context)
{
return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
}
}
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;
public class UsersAndRolesController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
public UsersAndRolesController() { }
public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
// GET: UsersAndRoles
public ActionResult Index()
{
return View();
}
}
}
var user = new ApplicationUser
{
UserName = "Ziyad",
Email = "email@domainname.com"
};
var password = "P@ssw0rd";
UserManager.Create(user, password);
var role = new ApplicationRole
{
Name = "Students"
};
RoleManager.Create(role);
UserManager.AddToRole("user_id", "role_name");
namespace UsersAndRoles.Controllers
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Web;
using System.Web.Mvc;
using Models;
public class UsersAndRolesController : Controller
{
private ApplicationUserManager _userManager;
private ApplicationRoleManager _roleManager;
public UsersAndRolesController() { }
public UsersAndRolesController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
public string CreateUser()
{
var user = new ApplicationUser
{
UserName = "Ziyad",
Email = "email@domainname.com"
};
var password = "P@ssw0rd";
var result = UserManager.Create(user, password);
if (result.Succeeded)
{
return "User created";
}
else
{
var msg = "Error, user not created";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
public string CreateRole()
{
var role = new ApplicationRole
{
Name = "Teachers"
};
var result = RoleManager.Create(role);
if (result.Succeeded)
{
return "Role created";
}
else
{
var msg = "Error, role not created";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
public string AddUserToRole()
{
var user = UserManager.FindByEmail("email@domainname.com");
if (user != null)
{
var result = UserManager.AddToRole(user.Id, "Teachers");
if (result.Succeeded)
{
return "User assigned to role";
}
else
{
var msg = "Error, user not assigned to role <br />";
foreach (var err in result.Errors)
msg += err + "<br />";
return msg;
}
}
else
{
return "User not found!";
}
}
}
if (User.IsInRole("Teachers"))
{
// role specific options
}
[Authorize(Roles = "Teachers")]
public ActionResult ActionName()
{
//teachers specific method
}
|