Every bit of research on this topic is showing how to do this tasks with MVC, my project is MVP webforms based. I have the authentication done, but is there a pattern or strategy to best do authorization?
Such as checking for hotlinking on specific pages against a user's role, or hiding ASP controls given a role.
Currently I'm doing things like:
if(user.Roles.Contains("Admin")){
lnkAdmin.Visibility = true;
}
And I don't think that's very clean or maintainable, is there a better way to do these things?
The Web Forms way of making specific controls available only to certain roles is to use a LoginView control. Example from the documentation:
<asp:LoginView id="LoginView1" runat="server">
<AnonymousTemplate>
Please log in for personalized information.
</AnonymousTemplate>
<LoggedInTemplate>
Thanks for logging in
<asp:LoginName id="LoginName1" runat="Server"></asp:LoginName>.
</LoggedInTemplate>
<RoleGroups>
<asp:RoleGroup Roles="Admin">
<ContentTemplate>
<asp:LoginName id="LoginName2" runat="Server" />, you are logged in as an administrator.
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
</asp:LoginView>
To prevent users not in certain roles from accessing pages, you can use the location elements in your web.config file. Again, another example from the documentation:
<configuration>
<system.web>
<authentication mode="Forms" >
<forms loginUrl="login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="20" >
</forms>
</authentication>
<!-- This section denies access to all files in this application except for those that you have not explicitly specified by using another setting. -->
<authorization>
<deny users="?" />
</authorization>
</system.web>
<!-- This section gives the unauthenticated user access to the Default1.aspx page only. It is located in the same folder as this configuration file. -->
<location path="default1.aspx">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
<!-- This section gives the unauthenticated user access to all of the files that are stored in the Subdir1 folder. -->
<location path="subdir1">
<system.web>
<authorization>
<allow users ="*" />
</authorization>
</system.web>
</location>
</configuration>
Similarly, it can be role based.
<location path="AdminFolder">
<system.web>
<authorization>
<allow roles="Admin"/> //Allows users in Admin role
<deny users="*"/> // deny everyone else
</authorization>
</system.web>
</location>
<location path="CustomerFolder">
<system.web>
<authorization>
<allow roles="Admin, Customers"/> //Allow users in Admin and Customers roles
<deny users="*"/> // Deny rest of all
</authorization>
</system.web>
</location>