Alan Alcock
Alan Alcock

Reputation: 787

ASP.NET MVC - Authenticate once and only once until session out

Setup

I am using custom Forms Authentication - all standard stuff.

In the Login action on my Account controller,

I registered a handler in global asax for the AuthenticateRequest event. In my handler,

Problem

I debug a request for the home page after I have logged in and note that the AuthenticateRequest handler in global.asax is hit more than once per page request. I've checked the HttpContext.Current.Request.Path and this is because each resource on my page (effectively, every HTTP GET) is firing the authenticate requet, so, GET jquery.js, GET logo.png etc...

Question

On the first handled AuthenticateRequest I go to the db and then set the HttpContext.Current.User to my custom principal. What would be a good way to avoid going to the db for subsequent HTTP GETs that cause the AuthenticatRequest to fire. Effectively, authenticate once and once only until the user closes their browser or until the Authentication Ticket expires.

TIA

Upvotes: 0

Views: 1558

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

Instead of using the AuthenticateRequest method in your Global.asax I would recommend you writing a global action filter. This way the action filter will apply only before executing some action and populate the User. In fact a custom [Authorize] attribute is the best way to achieve that:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            return false;
        }

        // TODO: go ahead and work with the UserData from the authentication cookie
        // basically all the steps you described for your AuthenticateRequest handler
        // except for checking the presence of the forms authentication cookie because
        // we know that at this stage it exists and the user was successfully authorized

        return true;
    }
}

Upvotes: 1

Related Questions