Last week I had an interesting question about Xamarin.Auth, a library that allows Xamarin apps to authenticate users via standard authentication mechanisms (OAuth2), and store user credentials.
You can see how I wrote the word “standard” in bold because as long as some OAuth2 service follows the standards, Xamarin.Auth should support it. So my answer to whether Xamarin.Auth will work with OneDrive’s OAuth mechanisms was clearly “of course, it does”.
I was wrong.
Let’s see how we can use OAuth2 with OneDrive. There’s very good documentation over at https://dev.onedrive.com/auth/msa_oauth.htm.
For your convenience, here’s an overview of what you will need for the implicit OAuth flow, the one we’d typically use in a mobile app:
- Client ID: can be generated at https://dev.onedrive.com/app-registration.htm, respectively at Microsoft Application Registration Portal (read on for more details)
- Access token endpoint (for implicit flow): https://login.live.com/oauth20_authorize.srf
- Redirection endpoint (for implicit flow): urn:ietf:wg:oauth:2.0:oob (this won’t work with Xamarin.Auth…but please read on)
- Scopes: offline_acces, onedrive.readonly, onedrive.readwrite, onedrive.appfolder (can be found here)
The problem with the ingredients above is that the format of the redirection endpoint (“urn:ietf:wg:oauth:2.0:oob”) is not supported by Xamarin.Auth. It is supposed to update the title of the browser so that a change can be detected and the access token can be extracted. For details, Google has a pretty nice documentation.
By the way: Xamarin.Auth (and I’m talking about version 1.3 here) is pretty picky about redirect formats. This for instance means that “localhost” won’t work either. It wants a real URL, otherwise it will either show an error page (potentially only shortly but still annoying) or bring up a blocking modal message box.
This means we have to configure our OneDrive app to allow another redirection endpoint. The solution is to create a web application instead. If you add a new platform at the Microsoft Application Registration Portal you can select between “web” and “mobile application”:
With the web app created we can allow the implicit flow (which is what we want for our mobile app) and we can configure the redirect URI and use something that keeps Xamarin.Auth happy:
In the example above I used “xamarin.com”. You should use your own website. Be aware that Xamarin.Auth will really redirect there! You don’t want it to redirect to a (potentially) malicious site.
Save and use the specified credentials in the Xamarin.Auth constructor. Of course, you can now also use the authorization code flow which you might need to obtain a refresh token.
Conclusion: this is not optimal. Pull requests to address the issues above are welcome and I invite you to contribute to Xamarin.Auth at https://github.com/xamarin/Xamarin.Auth