ASP.NET Role Provider vs Membership Provider

早过忘川 提交于 2019-12-06 16:47:21

add sections to web.config

  <location path="page-only-allowed-to-be-accessed-by-admin.aspx">
      <system.web>
         <authorization>
           <allow roles="admin"/>
           <deny users="*" />
         </authorization>
      </system.web>
   </location>

You may find this article interesting - the web.config demystified

EDIT:

The code for generating the Authorization ticket is in your code.

FormsAuthentication.SetAuthCookie(username, true);

which is implemented like so (using Red Gate's Reflector)

public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
    Initialize();
    HttpContext current = HttpContext.Current;
    if (!current.Request.IsSecureConnection && RequireSSL)
    {
        throw new HttpException(SR.GetString("Connection_not_secure_creating_secure_cookie"));
    }
    bool flag = CookielessHelperClass.UseCookieless(current, false, CookieMode);
    HttpCookie cookie = GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
    if (!flag)
    {
        HttpContext.Current.Response.Cookies.Add(cookie);
        current.CookielessHelper.SetCookieValue('F', null);
    }
    else
    {
        current.CookielessHelper.SetCookieValue('F', cookie.Value);
    }
}

The RoleProvider will get the roles for a given user, so when the web.config is inspected for allowed or denied roles/users for a given section of your application, the RoleProvider will get the roles for the user and then check against the allowed/denied roles and authorize if appropriate.

Use the Role Provider.

Once you have setup the role provider, and assigned roles to your users, you can use the <authorization> section of Web.config to restrict access to your various resources based on role membership.

I suggest you use the SqlRoleProvider if you have an SQL Server available. It is very flexible in that it can assign roles to user names without the users having to be registered first - specifically, you don't need to also use the SqlMembershipProvider (or in fact any membership provider). Ie. if you add the role "Student" to the user name "John", the SqlRoleProvider will simply associate that role with that user name, and everything just works.

Good luck!

If you have a set of restricted files in a folder you can resitrict the Roles to that folder in the web.config:

eg:

<location path="TeacherAdmin" allowOverride="false">        
  <system.web>
    <authorization>
      <allow roles="Teacher"/>
      <deny users="*,?"/>           
    </authorization>        
  </system.web>     
</location>

Note: The path attribute can also point to a specific aspx page

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