I am using the Cookie Middleware to authenticate the user. I have been following this official tutorial.
Inside my Startup class, an excerpt from my Configure method looks like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // ... // Cookie-based Authentication app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, AutomaticAuthenticate = true, AutomaticChallenge = true, Events = new CustomCookieAuthenticationEvents(app), }); // ... } The CustomCookieAuthenticationEvents class is defined as follows:
public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents { private IApplicationBuilder _app; private IMyService _myService = null; private IMyService MyService { get { if(_myService != null) { return _myService; } else { return _myService = (IMyService) _app.ApplicationServices.GetService(typeof(IMyService)); } } } public CustomCookieAuthenticationEvents(IApplicationBuilder app) { _app = app; } public override async Task ValidatePrincipal(CookieValidatePrincipalContext context) { string sessionToken = context.Principal.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Sid)?.Value; LogonSession response = null; var response = await MyService.CheckSession(sessionToken); if (response == null) { context.RejectPrincipal(); await context.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); } } } Since the dependency injection is not available at Startup.Configure (the services are not even registered at that point), I made a bit of a workaround:
- Pass IApplicationBuilder service to the
CustomCookieAuthenticationEventsclass - Fetch
IMyServiceupon first request inside a read-only property (singleton pattern)
tl;dr
My solution works, but it's ugly. There is no dependency injection involved, as it is not possible at that time.
The essence of the problem is that I must instantiate CustomCookieAuthenticationEvents. As far as I have read the source code, there is no way around this, because the UseCookieAuthentication throws an exception if I omit the options parameter.
Any suggestion how can one make my current solution nicer?
Service.Configure?Startup.Configure.