1

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 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

For some reason I thought the UseCookiePolicy() middleware was related to authentication policies, and I knew UseAuthentication or UseAuthorization did stuff with cookies, so I wasn't sure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.