2

I have an asp.net core project. two role exist in application. user role with limited access that can act in site, and admin role with complete access that can act in site and admin panel. for some of security reason I want Idle timeout of admin been short (about 30 min), and user role time out 1 day. for user role as a default I set this code

services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromDays(1);
        options.CookieName = "Session";
    });

how can config admin role IdleTimeout?

Mohammad Akbari
  • 4,486
  • 6
  • 43
  • 74

2 Answers2

1

Simply, you can't. Session timeout is global. However, you could implement a layer on top of it that manually times out the session. For example, when the session is started, you could add a session var with the current date and time. Then, you could add a global action filter that checks this session var and compares the datetime with your custom timeout for the particular user role. If the custom timeout has been exceeded, you can then destroy the session manually (Session.Abandon()). In order for this to work, your global session timeout will have to be the longest timeout possible (presumably for admins), and then your custom timeout(s) would then be for any roles with shorter timeout periods.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • I am really interested in this solution. Would you be able to provide an example of some sort? – Fluous Feb 22 '19 at 12:26
1

I guess the SessionMiddleware should be modified to setup different session's idle times.

Explanation:

AddSession registers a SessionOptions object as singleton in DI. This object is injected into SessionMiddleware. Unfortinately, it is injected into a constuctor. As we know, a middleware is constructed at app startup. Per-request dependency injection is possible to Invoke method only, and SessionMiddleware doesn't have the Invoke method accepting SessionOptions.

So the plan is:

  1. Fork SessionMiddleware and implement Invoke(HttpContext, SessionOptions) method.
  2. After AddSession call, replace SessionOptions registration.

For example:

services.Replace(new ServiceDescriptor(typeof(SessionOptions),
    provider =>
    {
        //you could resolve another dependencies here and determine user's role.
        var service = provider.GetService<FooService>();

        return new SessionOptions();
    },
    ServiceLifetime.Scoped));
Ilya Chumakov
  • 23,161
  • 9
  • 86
  • 114