Use Any Authentication Handler for all Actions in Asp.Net Core 2.0

Georg Dangl by Georg Dangl in Web Development Wednesday, November 08, 2017

Wednesday, November 08, 2017

Posted in DotNet Asp.Net Core

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.

Happy authenticating!


Share this post


comments powered by Disqus

About me

Hi, my name's George! I love coding and blogging about it. I focus on all things around .Net, Web Development and DevOps.

DanglIT

Need a consultant for BIM, GAEB or Software Development?

Contact me at [email protected], +49 (173) 56 45 689 or visit my professional page!

Dangl.Blog();
// Just 💗 Coding

Social Links