Membership roles made easy with Razor syntax in WebMatrix

Let’s see how easy it is to restrict access to certain pages based on roles. 

First, if you don’t have WebMatrix, DOWNLOAD IT HERE.  I am using the WebMatrix 2 Beta version released in September 2011.

We’re going to use the photo gallery site created in a previous post as a starting point.

First Run your website from WebMatrix and click Login.

01

Click Register.

02

Create an account by entering an email and password.  Notice the photo gallery template has CAPTCHA verification built-in, so you can tell whether a user is a human or computer by asking the user to read and enter extra words that a computer wouldn’t be able to read.

02-1

All you would need to do is uncomment out the corresponding code in Register.cshtml and replace the public and private keys, and register at reCAPTCHA.net

03

Notice under Databases, your newly created account is now under UserProfiles.  Take note of the UserId.

04

In your Databases, under webpages_Roles, type in a role name under RoleName (e.g. admin).

05

Hitting <Enter> will automatically assign a RoleId.  Remember this role ID.

06

Double-click webpages_UsersInRole.  We would like to assign our user with UserId 1 to the admin role, which corresponds to RoleId 1.  Enter these corresponding ID numbers to assign the user to the desired role. 

08

Now we’re going to exit our Databases and go back Files.  Right-click on your website name and create a New File…

09

Create a CSHTML file called AdminOnly.cshtml.  This will be the file only a user who is an admin can access.

10

Create another file and name it AdminError.cshtml.  This will be the file to which the user who is not allowed to access the previous file gets redirected.

11

Enter the following Razor syntax (or some variation thereof using your friend, IntelliSense) into your AdminOnly.cshtml file:

@if (Roles.IsUserInRole(“admin”))
{<span>welcome to the jungle </span>}
else
{Response.Redirect(“~/AdminError”);}

12

Enter the following Razor syntax (or some variation) into your AdminError.cshtml file:

<p>You must log in as an admin to access that page.</p>

13

Save both files.  Now try to access https://localhost:xxxx/AdminOnly (the local URL and xxxx can be found under Site above Files, Databases, and Reports or when you hit Run).

14

Log out of the admin account and try to access the same URL.

15