Open prabirshrestha opened 11 years ago
:+1: Important feature.
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.
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));
}
}
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.
Should also actually validate the expiry in code, rather than relying on cookie expiry