views:

93

answers:

2

My question is essentially the same as question 765054 on StackOverflow. I'm only asking it again because the accepted answer is incorrect (you can not access the session object in Application_BeginRequest).

Our use case is that we want to store the authenticated user's user object in the session. So in subsequent requests, we can correctly set the IPrincipal and IIdentity based on the user object in session.

A: 

I do similar things using a base controller and overriding OnActionExecuting. Whether this is the earliest it can be done or not, I don't know, but I do know that it will happen before your action is executed (and thus before the view is rendered). Alternatively you might want to have a custom authorize attribute that does what you want. This might be the only way to make sure that it's done prior to other attributes running.

tvanfosson
Just implemented the OnActionExecuting override and it worked like a charm. OnActionExecuting is called before the authorize filter so this solution will work for us.
Jason
+1  A: 

In your global.asax.cs file, you can handle the following

    protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
    {
        if (httpContext.User.Identity.IsAuthenticated)
        { 
        // if using forms authentication, retrieve and set your own
        // custom IPrincipal. You need to check for nulls, etc.
        ...
        }
    }

Create your own user class (implements IPrincipal) and replace the HttpContext.Current.User and System.Threading.Thread.CurrentPrincipal with your own. If you need to, you can create your own IIdentity class as well.

See my answer to a similar SO question.

I would advise against storing the user in the Session, and sometimes caching the User in Session is a performance win. It depends on how your site is used. With WebForms, I think the earliest that session is available is at PreInit.

Robert Paulson
Robert: The issue is that the session variable is not available when Application_OnAuthenticateRequest is executed.
Jason