Recently we had a couple of customers that needed to connect their native desktop and mobile applications to an OpenID Connect and OAuth 2.0 back-end.
We always had samples that showed how to do this, but making them re-usable and cross-platform was a bit harder than I originally thought. At the same time the IETF released some good guidance around OAuth 2.0 for native applications (draft-spec) that I wanted to incorporate.
The end result of that is IdentityModel.OidcClient, which is a PCL that runs on desktop .NET, WinRT/UWP and Xamarin iOS and Android. It encapsulates all the protocol and crypto work needed for OpenID Connect Hybrid Flow with PKCE and can reduce all those steps to a few lines of code:
var client = new OidcClient(options); var result = await client.LoginAsync();
The result object will contain the claims of the user as well as an access token and refresh token (if requested).
The second problem I wanted to solve is keeping the access tokens fresh without putting too much logic into the client application. This is done by an HTTP message handler that you can plug into HttpClient. The handler will add the access token to outgoing requests and try to refresh the token whenever it sees a 401 response. You would then use this one HttpClient throughout your code:
_client = new HttpClient(result.Handler); _client.BaseAddress = new Uri("https://demo.identityserver.io/api/");
To create such a library as a PCL was a combined effort – I’d like to thank Andrew Arnott for PCLCrypto and dvsekhvalnov for building Jose-Pcl on top. Without them JWT validation wouldn’t be possible.
I pushed a 1.0 to nuget – but there is still a lot of work. I opened a couple of issues already which are all up for grabs.
We also need more samples – Android, WPF and console hosts come to mind. Please support OidcClient and the above libraries by giving feedback and maybe contributing to them.