My project was built using ASP.NET Core 1.1. Later, updated to 2.0 because of the new requirements to use non-Core library. Thanks to fabulous .NET Standard! (for more information, see .NET Standard)

Initially, my implementation for multiple authorizations was something like as described here:

Yeah, something like this:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

While it did work perfectly, my Integration Tests project didn’t quite happy. It was working in 1.1, but not suddenly, because of this.

Fast forward.

Just exactly one day before the official ASP.NET Core 2.1 roadmap announcement, I discovered the so-called “Virtual Schemes” on GitHub.

According to this,

It provides dynamic scheme selection based on a DefaultSelector action. That code isn’t using anything new from 2.1, so you could copy it as is into a 2.0 app.

so I did copy that awesome code from ASP.NET Core 2.1:

https://github.com/aspnet/Security/blob/e69d9e20635abcc8ae46970f819397b717b2527a/src/Microsoft.AspNetCore.Authentication/VirtualAuthenticationHandler.cs

Show me the code!

Note that I am using IdentityServer4, a free, open source OpenID Connect and OAuth 2.0 framework for ASP.NET Core.

Not a complete code, but yeah, something like this.

As you can see, now that all controllers are protected by [Authorize] by default, thanks to the global filter policy.

URL starts with /api/ works with JWT token only, as expected. Other than that, fallback to whatever you define in Virtual Scheme.

Bonus, your Integration Tests project will thank you for not dealing with faking JWT token, etc. You can just simply inject a custom middleware for this purpose, something like:

identity.AddClaim(new Claim("sub", user.Id));

identity.AddClaim(new Claim("email", user.Email));

//...

httpContext.User.AddIdentity(identity);

await _next.Invoke(httpContext); // invoke next middleware

Summary

By combining one of the cutting edge version of modern ASP.NET Core 2.1 features called Virtual Scheme (tentatively?), you can have a better, clean, more control over the authorization/authentication schemes.

Handling authorization in Integration Tests project also can be done easily by implementing a simple middleware.

[Update: VirtualScheme might be renamed to PolicyScheme. You might want to watch this PR: https://github.com/aspnet/Security/pull/1665 ]

[Update: Related post: https://medium.com/@joni2nja/using-policyserver-local-gotcha-upgrading-from-asp-net-core-2-0-to-2-1-1e7034598a4d]