在网络表单中进行授权的最佳方式

Best way to do authorization in webforms

关于这个主题的每一点研究都在展示如何用 MVC 完成这个任务,我的项目是基于 MVP webforms 的。我已经完成了身份验证,但是是否有一种模式或策略可以最好地进行授权?

例如根据用户角色检查特定页面上的热链接,或隐藏给定角色的 ASP 控件。

目前我正在做这样的事情:

if(user.Roles.Contains("Admin")){
     lnkAdmin.Visibility = true; 
}

而且我认为这不是很干净或可维护的,有没有更好的方法来做这些事情?

使特定控件仅对特定角色可用的 Web 窗体方法是使用 LoginView 控件。文档中的示例:

 <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>

要防止不属于特定角色的用户访问页面,您可以在 web.config 文件中使用 location 元素。同样,文档中的另一个示例:

<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>

同理可以是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>