ASP.NET Core - Can UseSession() be used before UseAuthentication() and UseAuthorization()?

274 Views Asked by At

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?

1

There are 1 best solutions below

1
On BEST ANSWER

Neither UseAuthentication nor UseAuthorization are the Cookie Policy Middleware which is added for example by UseCookiePolicy (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 order of middleware is important. Call UseSession after UseRouting and before MapRazorPages and MapDefaultControllerRoute. See Middleware Ordering.

The ordering doc you have already linked and the only additional order description I found there applicable to the situation is the following:

UseCors, UseAuthentication, and UseAuthorization must appear in the order shown.

Based on the docs and quick code peek into the session middleware it should be ok to use it before the auth ones:

app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();