Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.

Checking only for Request.IsLocal works fine.

if(Request.IsAuthenticated)
{
  if(User.IsInRole("Admin");
    MiniProfiler.Start(); 
}

Any idea or why it's not working or better way to do it?

[Update] I accepted the awnser but undid it as I didn't quite get it do work

I did the following but the profiler is not showing up at first. After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.

protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
        if (User.IsInRole("Admin"))
        {
            HttpCookie cookie =   HttpContext.Current.Request.Cookies.Get("RoleProfiler");
            if (cookie == null)
            {
                cookie = new HttpCookie("RoleProfiler");
                cookie.Value = "yes";
                cookie.Expires = DateTime.Now.AddDays(1d);
                Response.Cookies.Add(cookie);
            }
        }
 }

And I'm checking with

protected void Application_BeginRequest(Object sender, EventArgs e)
{            
        HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
        if ((cookie != null) && (cookie.Value == "yes") )
        {
            MvcMiniProfiler.MiniProfiler.Start();
        }
 }

And ending at the end of the request.

protected void Application_EndRequest()
{
        MvcMiniProfiler.MiniProfiler.Stop();
}

[Update2] Closing question, ignore this, I was being owned by outputcache.

like image 352
Tadeu Maia Avatar asked Jun 14 '11 19:06

Tadeu Maia


1 Answers

The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:

protected void Application_BeginRequest()
{
   MvcMiniProfiler.MiniProfiler.Start();  
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
  if(!CurrentUserIsAllowedToSeeProfiler())
  {
    MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
  }
}
like image 99
Sam Saffron Avatar answered Sep 21 '22 13:09

Sam Saffron