Following on from basic Access Rights for registered users, we now look at how to assign privileges based on roles.
We will be using the default AspNet user database packaged with Visual Studio for this.
If we wish to create a batch of web forms to be restricted by a specific role, start by creating a new folder in your solution.
Right-click the solution in Solution Explorer, expand over 'Add' and select 'New Folder'.
Name this folder appropriately, remembering it will appear in the URL of the web forms within.
We have called ours 'Admin'.
By right-clicking on this folder and selecting to add a new item, select a Web Configuration File from the Web-General section.
You may leave its name as the default Web.config.
Change its script to reflect the code below.
<location path=""> ensures all items in this folder are included in the restrictions.
We use <allow roles="Role1, Role2" /> to list the named roles that will be permitted to access these pages, separating each with a comma.
We use <deny users="*" /> to ensure all other users do not have access.
That's it...we have enforced restrictions based on user roles.
So how do you create and assign roles?
The default AspNet database includes 3 tables representing the relationship between Users and Roles. There is theoretically a many-to-many relationship between Users and Roles but as this is not physically possible to model a link-table is created called UserRoles.
Below shows a conceptual model for the many-to-many relationship showing that each user can be assigned multiple roles, and each role can be assigned to multiple users.
The second conceptual model shown is for the one-to-many relation between a User and their multiple User-Roles, and each Role has multiple Role-Users. A single record in UserRoles is attributed to a single User and a single Role.
When a user is registered using the default AspNet web forms, a record is created in AspNetUsers, but no Roles or UserRoles are ever assigned.
You must therefore first create AspNetRoles (such as 'Guest', 'Member', 'VIP', 'Admin') and secondly create records in AspNetUserRoles to link the primary key of every user to each of their roles.
We recommend registering a few users in the web form, then manually edit the database directly to have some test data.
For example, if we have two users we might allocate roles thusly:
Our test data may look like this:
Our web.config file we used the AspNetRoles 'Name' field, not the ID.
While we used numbers for the Id property of AspNetRoles, it is in fact an nvarchar so will allow text string data.