asp.net folder authorization

不想你离开。 提交于 2019-12-11 14:11:28

问题


I'm using my own database and forms authentication.

The database contains one table with users and second one with roles, that users are assigned to.

The question is: how to prepare the section in web.config, so it allows acces to the folder only for users belonging to one of the roles?

Second question: Using IIS configuration I can block direct access to all folders in the web directory. Let's say, that one of pages will contain links allowing to download files from those protected folders. If user is allowed to acces that site will he also be able to download that content?


回答1:


Here is a sample web.config, if you placed this file within a folder (within the structure of your web project) where you only want to allow users with the "Admin" Role (for example) this will do the job.

<?xml version="1.0"?>

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

In order to link this to your security, after a successful login check you need to create a FormsAuthenticationTicket and pass in details like the user name and user roles.

A simple example showing this is:

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

That way you can do this in your code:

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

And your Web.config file will work as I detailed above.

More info on FormsAuthenticationTickets here http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx




回答2:


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



来源:https://stackoverflow.com/questions/2268323/asp-net-folder-authorization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!