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

Ado*_*ola 2 asp.net authorization webforms

关于这个主题的每一项研究都展示了如何使用 MVC 来完成这项任务,我的项目是基于 MVP Webforms 的。我已完成身份验证,但是否有最好的授权模式或策略?

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

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

if(user.Roles.Contains("Admin")){
     lnkAdmin.Visibility = true; 
}
Run Code Online (Sandbox Code Playgroud)

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

mas*_*son 7

使特定控件仅对某些角色可用的 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>
Run Code Online (Sandbox Code Playgroud)

要防止不具有特定角色的用户访问页面,您可以使用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>
Run Code Online (Sandbox Code Playgroud)

同样,它可以是基于角色的

<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>
Run Code Online (Sandbox Code Playgroud)