I'm working on an ASP.NET code base that uses sessions, authentication, and authorization.
They are initialized in the following order:
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
The Middleware Order documentation shows app.UseSession()
after the other two, but the documentation later says:
Session Middleware (UseSession) establishes and maintains session state. If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.
Emphasis mine.
Our app uses custom authentication code to handle different flows, and one of these initializes some data inside of sessions.
Because of this, placing the app.UseSession()
method after the authentication/authorization middleware causes the app to crash when that flow is triggered.
Is is safe to leave app.UseSession()
before the other two?
Neither
UseAuthentication
norUseAuthorization
are the Cookie Policy Middleware which is added for example byUseCookiePolicy
(see EU General Data Protection Regulation (GDPR) support in ASP.NET Core).The Session and state management in ASP.NET Core doc mentions the following about the order:
The ordering doc you have already linked and the only additional order description I found there applicable to the situation is the following:
Based on the docs and quick code peek into the session middleware it should be ok to use it before the auth ones: