NancyFx / Nancy

Lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono
http://nancyfx.org
MIT License
7.16k stars 1.47k forks source link

support for sliding expiry in forms auth #704

Open prabirshrestha opened 11 years ago

grumpydev commented 11 years ago

Should also actually validate the expiry in code, rather than relying on cookie expiry

Crisfole commented 10 years ago

:+1: Important feature.

Crisfole commented 10 years ago

https://gist.github.com/Crisfole/9249044

The above seems to be working for me. It'd be even simpler if you had access to FormsAuthentication.cs's private members. As it is it's pretty straightforward. I commented with things that would need to change for this to be integrated w/ the project.

There are no tests. That'd be important.

mike-ward commented 9 years ago

I use a base NancyModule where I can add a module hook:

        var timeout = Convert.ToInt32(ConfigurationManager.AppSettings["sessionTimeout"]);
        After += ctx => EnsureSlidingExpiry(ctx, timeout);

And a static method I stole from an old post:

    private static void EnsureSlidingExpiry(NancyContext context, int minutes)
    {
        if (context.CurrentUser == null) return;
        var formsAuthCookieName = FormsAuthentication.FormsAuthenticationCookieName;
        if (context.Request.Cookies.ContainsKey(formsAuthCookieName))
        {
            var formsAuthCookie = HttpUtility.UrlDecode(context.Request.Cookies[formsAuthCookieName]);
            context.Response.WithCookie(formsAuthCookieName, formsAuthCookie, DateTime.UtcNow.AddMinutes(minutes));
        }
    }
aharin commented 9 years ago

Is cookie-based sliding expiration is really a good feature? Sending cookies on get requests is probably not such a good thing, especially for requests that should be cacheable. The same functionality (auth timeout for idle users) can already be achieved without any changes to Nancy code. Consider creating a session token when user authenticates and store this token associated with the user in a database. Now let's use a guid id of the token rather then that of the user as the content of Nancy's auth cookie. IUserMapper will be now retrieving CurrentUser via the auth token id, and can check the time stamp or update expiry of the token server side.