Refresh ASP.NET Role Provider

≯℡__Kan透↙ 提交于 2019-12-06 02:56:22

I assume you have something like this in your web.config:

<roleManager enabled="true" defaultProvider="..." 
             cacheRolesInCookie="true">

The roles are cached in a cookie , so you can force them to refresh by deleting the cookie. This method worked for me. I added the cookieName attribute so that I don't rely on asp.net's default. For your scenario, though, you may be able to just set the cookieTimeout attribute to something reasonable and be done with it.

This method won't update the roles immediately, of course. They will be updated on the next page load after you delete the cookie.

Oscar Renesys

Refresh just need to delete the cookie:

For C#: Roles.DeleteCookie(); // Works as Roles.Refresh()

If you don't want to use cookies you can use Session object to cache the roles. like this:

        public override string[] GetRolesForUser(string username)
    {
        System.Web.SessionState.HttpSessionState Session = HttpContext.Current.Session;
        if (Session["roles"] == null)
                Session["roles"] = MyDataProvider.Security.GetRolesForUser(username);
        return (string[])Session["roles"];
    }

When you need to update the roles for this user you can do

Session["roles"] = null

depend on the custom role provider used.

Just call a "update my role" function on every request? (bad way but at least your sure to update it)

The roles are cached in a cookie (encrypted of course). The simplest solution will be to disable caching in the web.config file. You will loose some performance.

Else you must somehow resend the auth cookie. One major problem is that many browsers will not accept cookies on redirects with method post.

The other solution that worked for me:

1) In a aspx methodod log the user out and store the username in the session

//Add User to role reviewer and refresh ticket

Roles.AddUserToRole(User.Identity.Name, Constants.ROLE_REVISOR);
FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(User.Identity.Name, false); //Might work in some browsers
Session["REFRESHROLES"] = User.Identity.Name;
Response.Redirect("someprotectedurl?someid=" + someid);

2) In the loginpage sign the user in again if username is stored in session

protected void Page_Load(object sender, EventArgs e)
{
   string returnUrl = Request.QueryString["ReturnUrl"];
   if(String.IsNullOrEmpty(returnUrl) == false)
   {

         if(Session["REFRESHROLES"] != null)
         {
            if(!string.IsNullOrEmpty(Session["REFRESHROLES"].ToString()))
            {

               FormsAuthentication.SetAuthCookie(Session["REFRESHROLES"].ToString(), false);
               Session.Remove("REFRESHROLES");
               Response.Redirect(returnUrl);  
               return;
            }
         }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!