In Single Page Applications, it's common to use Bearer authentication, for example with OAuth2 integration, to make the API available to client applications. While this can also be used on the web frontend, I enjoy the simplicity of the Cookie based authentication that's the default for Asp.Net Core Identity projects.
Unfortunately, the latest release of Asp.Net Core 2.0 introduced a behavior that's different: There is only one default authentication scheme, others are only invoked and challenged when it's further specified, for example with an [Authorize] attribute or a policy. Shawn Wildermuth wrote a good post about that. I didn't want to clutter my code with annotations everywhere, and I also wanted to use multiple authentication schemes on non-authorized controllers to get user info, no matter if the request is done via Cookie or Bearer authentication.
Luckily, you can get the old behavior back: By defining a global catch-all policy that specifies all supported authentication schemes. It's simple to set up:
First, you configure all authentication methods in your Startups ConfigureServices method, in the example it's the regular Asp.Net Core Identity cookie authentication and IdentityServer4s OAuth2 functionality.
In the configuration for MVC,there's a defaultPolicy which specifies all authentication schemes used in your app. Since policies mandate at least one requirement, we'll add an assertion that simply returns true for all requests: .RequireAssertion(c => true). The effect of the policy is now that it doesn't enforce authentication, but tries to challenge all schemes. So without further configuration, your actions should now make use of either Cookie or Bearer authentication. If required, the policy can be further tweaked to define exceptions where it's not applicable.