Using OAuth2 Middleware with ASP.NET Core 2.0

It should be simple, but documentation doesn’t help (yet?)

ASP.NET Core 2.0 documentation is not yet 100% complete, unfortunately, and in the last days I had some hard time figuring out how to use OAuth2 authentication to authenticate a ASP.NET Core 2.0 application against our OAuth2 endpoint.

Documentation, right now, tells you how you can use pre-configured OAuth2-based services for the most common social platform, like Facebook and Twitter, but nothing is said if you need to authenticate against a custom OAuth2 server.

As the RTFM rules says, I’ve started reading the manual and, more specifically, I’ve started from here, since I was interested in the “external providers” part:

After having read all the documentation and understood what happens behind the scenes, I moved to read the following document but, again, no mention on how to deal with custom OAuth2 providers.

As you may have noticed, it is just a list of common OAuth2 providers and that’s it! No additional info given. To work with them, you have to figure out yourself. Not a really informative read.

So, since documentation does not help (and this is very bad), but at least ASP.NET Core source code is available on GitHub (and this is very good) I started from there and, specifically from the “SocialSample” example:

here you can see how authentication against Google, for which there is no dedicated pre-built authentication middleware, works.

After having studied that, I was able to correctly configure the OAuth2 middleware in order to work with our OAuth2 provider. To get some help to figure out what all the options are for, you can use Microsoft.AspNetCore.Authentication.OAuth help page:

I’ve published a gist here, where I encapsulated the configuration into an helper class, to make sure it will be easier next time:

to use it, it just need to be called in the AddOAuth method in the ConfigureServices method of the Startup class:

options => AuthenticationMiddleware.SetOAuth2Options(options)

This is probably the easiest way to do that. In our case I preferred to go a little further and create a dedicated authentication middleware for our Sensoria endpoint, so that I could also create a NuGet package to be used in all our other projects.

I’ve just looked at how Microsoft did it for Facebook, for example, and from there I created mine.

If you don’t need to create a provider for your own OAuth2 endpoint, but just need to connect to a common service, like GitHub, Reddit, Slack or many others, you may be interested in knowing the AspNet.Security.OAuth.Providers project aim to create and provide a collection of security middleware to support all the common social authentication providers. Just keep in mind that right now only ASP.NET Core 1.0 is supported.