asp.net文件夹授权

问题描述:

我正在使用我自己的数据库和表单身份验证。asp.net文件夹授权

数据库包含一个带有用户的表格,第二个带有角色的表格分配给用户。

现在的问题是:如何准备web.config中的部分,因此它只允许属于某个角色的用户访问该文件夹?

第二个问题: 使用IIS配置我可以阻止直接访问Web目录中的所有文件夹。比方说,其中一个页面将包含允许从这些受保护的文件夹下载文件的链接。如果用户被允许访问该网站,他是否也可以下载该内容?

这里是一个示例web.config,如果您将该文件放在一个文件夹内(在您的Web项目结构中),您只希望允许具有“Admin”角色的用户(例如),这将执行工作。

<?xml version="1.0"?> 

<configuration> 
    <appSettings/> 
    <connectionStrings/> 
    <system.web> 
     <authorization> 
      <allow roles="Admin"/> 
      <deny users="*"/> 
     </authorization> 
    </system.web> 
</configuration> 

为了成功登录后,该链接到您的安全,请您需要创建的FormsAuthenticationTicket,并通过在如用户名和用户角色的详细信息。

一个简单的例子显示出这是:

FormsAuthenticationTicket myTicket = new FormsAuthenticationTicket(1, myUserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, myUserRole, FormsAuthentication.FormsCookiePath); 
string hash = FormsAuthentication.Encrypt(myTicket); 
HttpCookie myCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); 
Response.Cookies.Add(myCookie); 

这样,你可以在你的代码做到这一点:

if (Context.User.IsInRole("Admin")) { 
     // Do Something 
} else { 
     // Do Something Else 
} 

而且Web.config文件将工作,我上面详述。在FormsAuthenticationTickets

更多的信息在这里http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx

+0

我知道。但是存在一个问题,即分配给用户的角色存储在我自己的数据库/表中。有没有办法用web.config以某种方式连接该表? – Charly 2010-02-15 19:19:15

+0

答案已修改,以包含更多详细信息请求 – 2010-02-15 19:26:11

+0

我已使用Cookie身份验证。但是,纠正我,如果我错了:元素“”中的web.config使用元素myUserRole中的cookie中存储的数据? – Charly 2010-02-15 20:07:31

<appSettings/> 
<connectionStrings/> 
<system.web> 
    <authorization> 
     <allow roles="Admin"/> 
     <deny users="*"/> 
    </authorization> 
</system.web>