In order to group users who may have authorisation to access specific pages or functionality, we typically assign them to roles. In order to do this we use ASP.NET Identity's RoleManager class. This is created in a similar way to the UserManager we used in the Identity tutorial, by first creating a DbContext, then a roleStore and finally creating the roleManager, as per the example below:
For the code above to work you will also need to add the following
var identityDbContext = new IdentityDbContext("IdentityConnectionString"); var roleStore = new RoleStore<IdentityRole>(identityDbContext); var roleManager = new RoleManager<IdentityRole>(roleStore);
usingstatements at the top of the appropriate .cs file
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework;
The roleManager object can now be used to create, edit and delete roles - example code to create a role is shown here:
IdentityRole adminRole = new IdentityRole("admin"); roleManager.Create(adminRole);
It can also be used to get a collection of roles as follows:
These roles could be iterated through if desired.
var allRoles = roleManager.Roles;
The process of adding a user to a role is the responsibility of a UserManager not a RoleManager however. The code below assumes we have an instance of a userManager and an instance of User (example code for this can be found in the Identity tutorial) and shows how to add a user to a role:
Be aware that for the changes to take place, the user will either need to log out and back in again, or be logged in again programmatically.
userManager.AddToRole(user.Id, "Admin"); userManager.Update(user);
Add a web.config file to the folder within your website that you wish to secure. See below for example contents of a web.config file which restricts access to users that are logged in (by denying access to anonymous users)
<?xml version="1.0"?> <configuration> <system.web> <authorization> <deny users="?"/> </authorization> </system.web> </configuration>
deny entry can be used to specify names of roles or users (multiple values can be separated by commas).
? (as in the above example) refers to anonymous users and
* refers to all users
In addition to
allow can be used to permit users. Multiple rules can be added, and will be applied from bottom up (that is rules will override those below them).