So things have been a bit quiet lately, I have been pretty busy at work and actually ended up a bit under the weather for a while, but am recovering now and want to continue on with this series of posts.
Last time I wrote about authenticating on Xamarin Form to Autodesk Forge using a web view to handle the authorization events. The use of webviews is being discouraged in some areas. It has been hard to get to the reasoning behind this, but some people are saying that it is possible for an attacker to fake in their own malicious site to replace the authentication page. I’m not sure how much of a worry this is, especially in mobile where both the app and the webview are sandboxed. Instead Google is recommending that you use the system browser directly. If nothing else, it will at least allow your user to use single-sign-on.
So how do we do this? First of all you have to modify your Autodesk Forge app to specify a different callback URL, one with your custom protocol. In my case, I used bbsw-fm://brainbucketsoftware.com.
Now when you start your authentication, instead of telling the webview to navigate you use the Device.Url command such as below (formatted for the blog, but obviously all one line).
string BaseUrl = "https://developer.api.autodesk.com/authentication/v1/authorize"; private const string ResponseType = "code"; private const string ClientId = "xxxxxxxxxxxxxxxxxxxxxxx"; private const string ClientSecret = "yyyyyyyyyyyy"; private const string Scope = "data:write%20data:read%20data:create"; private const string CallbackUrl = "bbsw-fm://brainbucketsoftware.com/"; private const string CodeParameter = "?code="; string url = $"{BaseUrl}?response_type={ResponseType}&client_id={ClientId}&redirect_uri={CallbackUrl}&scope={Scope}"; Device.OpenUri(new Uri(url));
The next thing we need to do is override the OnAppLinkRequestReceived method in the App.xaml in your shared/portable project.
protected override async void OnAppLinkRequestReceived(Uri uri) { base.OnAppLinkRequestReceived(uri); // same code as was used in the webview sample bool retrievedToken = await GetAccessTokenAsync(uri.ToString()); if (retrievedToken) await NavigationService.NavigateAsync(Pages.Test); }
The above function is supposed to be called automatically by the Xamarin Forms objects when your registered protocol is invoked on the device. However, I found that it only worked on Android and wasn’t being called on iOS or UWP (I believe there was a bug filed for this with Xamarin). So I created another entry point in my App object for those platforms which I ended up calling manually in the platform specific code.
public void UwpIOSOnAppLinkRequestReceived(Uri uri) { OnAppLinkRequestReceived(uri); }
Next post we will take a look at what we need to do for UWP platform code.
Pingback: Xamarin Forms, Autodesk Forge Access Token « random bits and bytes