ASP.NET Web Pages – Restricting Access
[ This is a 5 part tutorial; previous tutorial, Delete Roles ]
Roles are meant to be used as an access level. Here we will make a folder and restrict access to it, allowing only admins to access it. Create a folder and name it Webmaster, insert a _PageStart file and copy this:
@{ Layout="~/_Sitelayout.cshtml"; WebSecurity.RequireAuthenticatedUser(); if (!Roles.IsUserInRole("Admin")){ Response.Redirect("~/restricted/error.cshtml"); } }
Here, the bottom code uses the Roles class and we check if the current logged-in user is in the role Admin. If they are, they can browse this directory; otherwise redirect them. Create a new folder, name it restricted and add an error.cshtml file, and put some text it. Then do the following:
- Register yourself with a new account
- Add a new role called Standard
- Add the new user in the standard role
- Browse the Webmaster directory
When you attempt to browse the directory you won’t be able to; it will redirect you.
Summary
Roles are ideal when you want full control over your users. They are extremely useful for large websites like e-commerce websites, as you might have customers, staff, and admins. Roles are an access level control and allow you to restrict certain parts of the website to unauthorized users.