I am developing small department-size application using Web Forms. Technology choice comes form the past, as application is based on an old one already existing + Web Forms seem to be extremely fast and efficient for our case.
Default template in VS 2015 creates all login pages, etc. I assign roles to users. And the question comes how to protect specific folder or page to be available only for users with specific role?
The only idea I have is:
If Not Page.User.Identity.IsAuthenticated or Not Page.User.Identity.IsInRole("MyRole") Then
Response.Redirect("~/Account/Login?ReturnUrl=" & Server.UrlEncode(Request.Url.ToString())
[Authorize( Roles = Constants.ADMIN )]
You can restrict access to pages and folders in your Web.config, instead of writing
If Then Else code on each page.
Restricting access to a particular page to specific roles
<location path="SecureFolder/SecurePage.aspx" > <system.web> <authorization> <deny users="*"/> <allow roles="Manager,Admin"/> </authorization> </system.web> </location>
Restricting access to a particular folder to a specific role
<location path="AdminFolder" > <system.web> <authorization> <deny users="*"/> <allow roles="Admin"/> </authorization> </system.web> </location>
You repeat the
<location> element for all pages and folders in your application you need to secure.
More information on MSDN here: https://support.microsoft.com/en-us/kb/316871
Folder level Web.config example
An alternate to putting everything in the main Web.config of your web application, is to create a Web.config file in each of the folders you need to secure. When doing this, you don't need anything else in the folder's Web.config file, and you don't need to include the
e.g. instead of putting the AdminFolder config in your main Web.config file, you can create a new Web.config file inside the AdminFolder directory which only contains the following code.
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <authorization> <allow roles="Admin" /> <deny users ="*" /> </authorization> </system.web> </configuration>