In my previous entry I’ve blogged on how to implement federated authentication to an external identity provider using the System.IdentityModel subsystem and the WS-Federation. This entry shows how to implement OAuth2 federated authentication (Google, Facebook) with the DotNetOpenAuth library.
Let’s start as usual – a simple web app with two pages, the Default page and the LoginPage. Add an authorization rule and forms authentication redirect to the LoginPage for requests that are not authenticated:
From the NuGet package manager, install the DotNetOpenAuth.Ultimate package (a standalone complete DotNetOpenAuth).
The passive OAuth2 (the authorization_code flow) requires the client_id and client_secret parameters (these two kind of authenticate the application at the identity provider side) as well as three Uris: the authentication uri (this is where the browse is redirected to authenticate users), the token uri (this is where the one-time code returned from the login page is exchanged for an access_token) and the profile uri (which is a part of a graph API and allows the application to retrieve user profile information).
Let’s take Google for example. They have the OpenID Connect Discovery uri where a current information on authentication uris is published. This is where you get the information on all three required uris.
To get client_id and client_secret you need to register your application at the Google Console projects page. You need to create a new project, go to APIs&auth/Credentials, register a redirect uri (a uri in your app Google should redirect back to) and they generate both the client_id and client_secret.
Also remember to go to APIs&auth/APIs and switch Google+ API to ON (or your profile API calls will end up with 403)!
Be warned that some details of OAuth2 Google authentication have changed lately and are subjects for further changes.
When you are ready, go back to Visual Studio.
We are going to use the WebServerClient class which is designed to handle the OAuth2 authorization_code flow. We inherit from it to provide all Google endpoints:
We also need a helper class to deserialize JSON profile information
and a technical helper class to strip off unnecessary query string parameters from the web API calls
Actual OAuth2 flow code is straightforward now
The Google Client is just