在webforms中进行授权的最佳方式

时间:2015-01-30 14:20:38

标签: asp.net webforms authorization

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

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

目前我做的事情是:

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

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

1 个答案:

答案 0 :(得分:2)

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>