Xamarin Forms and Autodesk Forge

Introduction

I am going to change things up a bit and talk about working with Autodesk Forge on Xamarin Forms apps. If you are unfamiliar with Autodesk Forge, it is a set of web services that implement a range of functionality that in the past you might have only seen on desktop CAD programs. Forge gives you viewing, data management and some other services that may be of interest if you are in to processing designs. For the purposes of this article, we will look at authenticating a Xamarin app with Forge.

App Creation

The first thing you have to do is create an app with Forge. This is a pretty simple process. You login to developer.autodesk.com. Pull down the drop down menu showing your name and tap “My Apps”. You can then tap “Create App”.

ForgeCreateApp

Most of what you see is pretty straight forward. Pick the api’s that you are interested in and fill in the app name, description, callback url and website url.

Even if you are doing a mobile app, you still need to supply a callback url. This url will be used when the user authenticates.

ForgeappcreatedOnce the app is created, you should see something similar to what I have shown on the left. The important information is the client ID and the client secret. You will be needing this information for authenticating the user.

OAuth

Forge uses OAuth 2.0 throughout its services for authentication. There are a lot of mixed feelings about OAuth: some think it is very painful and clunky. To be honest, I don’t find it too bad and I think the effort is worth it as then you don’t have to worry about secure storage of user ids and passwords.

If you are unfamiliar with OAuth, it is a bit of a mix of separately authenticating outside of your app with a service and then authorizing your app to use the services in your name. Your app will use the client id and secret to connect to the service with requested access levels, the service will allow you to authenticate, and if all goes well, you will receive an access token that is used to consume the services. At no point does your app handle user ids and passwords. If you have ever given an app on your phone access to use your twitter account or Facebook account, you have probably used OAuth.

So lets take a look at how this would be implemented in your Xamarin app.

Setting Up Authentication

In your Xamarin app, you are probably going to want to connect to Forge as the very first thing, so you should navigate to that page upon app initialization. In my sample app, I am using the Prism framework and you can see samples of how that works in previous blog articles.

I have setup a ContentPage as the login page and it only contains a WebView control. On the WebView control, I am adding an event handler for the Navigating event. On the ContentPage, I am just overriding OnAppearing.


<?xml version="1.0" encoding="utf-8" ?>
<ContentPage     xmlns="http://xamarin.com/schemas/2014/forms"     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"     xmlns:helpers="clr-namespace:Fusion.Mobile.Helpers;assembly=Fusion.Mobile"     xmlns:behaviors="clr-namespace:Fusion.Mobile.Behaviors;assembly=Fusion.Mobile"     xmlns:effecs="clr-namespace:Fusion.Mobile.Effecs;assembly=Fusion.Mobile"     x:Class="Fusion.Mobile.Views.LoginPage">

    <Grid>
        <WebView x:Name="_webViewer" Navigating="_webViewer_Navigating" />
    </Grid>

</ContentPage>

The OnAppearing override in the ContentPage is pretty straight forward and only serves to direct the WebView control to the Forge authorization page.


protected override void OnAppearing()
{
    base.OnAppearing();
    StartAuthentication();
}

The StartAuthentication method is used to set the WebView control to the Forge authentication page, and this is accomplished with a long url constructed from a number of parameters. It looks like the following:

https://developer.api.autodesk.com/authentication/v1/authorize
?response_type={resptype}
&client_id={clientid}
&redirect_url={callback}
&scope={scope}

I reformatted the above into multiple lines for readability, but normally, it is all one line. The {resptype} value is “code”. The {clientid} and {callback} values are the values from when you created your Forge app. And scope is the level of access you require to the data. In our case, we are just going to use “data:read”.


private const string BaseUrl = "https://developer.api.autodesk.com/authentication/v1/authorize";
private const string ResponseType="code";
private const string ClientId = "[your client id]";
private const string ClientSecret = "[your client secret]";
private const string Scope = "data:read";
private const string CallbackUrl="[your callback url]";
private const string CodeParameter = "?code=";

private void StartAuthentications()
{
    string url = $"{BaseUrl}?response_type={ResponseType}&client_id={ClientId}&redirect_url={CallbackUrl}&scope={Scope}";
    _webViewer.Source = new UrlWebViewSource { Url = url };
}

Let’s recap. We have our first page in our app, which contains a WebView control. After the app initializes and the first page is displayed, it executes our overridden OnAppearing method. This method constructs the url for the user to authenticate with Forge and authorize the app. It then passes the url to the WebView control and the user is then able to authenticate.

This is where it gets a bit tricky. You have to pay attention to the Navigating event. Once the user successfully authenticates, the WebView control will try and navigate to your callback URL. You can sniff that out by looking to see if the url that is being navigated to is your callback url. Take note: there could be multiple calls to this event handler as the WebView control handles multiple navigations. Once you find the url that has your callback url, grab it! You will need to pull out the code parameter at the end of the url. Then, cancel the navigation of the WebView. After that, we need to get the access token that is used to show that calls made from this app are authorized.


private const string CodeParam = "?code=";

private async void _webviewer_Navigating(object sender, WebNavigatingEventArgs e)
{
    if (e.Url.StartsWith(CallbackUrl))
    {
        int pos = e.Url.IndexOf(CodeParam);
        string code = e.Url.SubString(pos + CodeParam.Length);
        e.Cancel = true;

        await GetAccessToken(code);
    }
}

We are almost finished authenticating and authorizing! All we need to do now is retrieve our access token. To do this, we are just going to POST a REST call.


private async Task GetAccessToken(string code)
{
    using (HttpClient client = new HttpClient())
    {
        client.DefaultRequestHeaders.Clear();
        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://developer.api.autodesk.com/authentication/v1/gettoken"))
        {
            request.Content = new StringContent(
            $"client_id={ClientId}&client_secret={ClientSecret}&grant_type=authorization_code&code={code}&redirect_uri={CallbackUrl}");
            request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            using (HttpResponseMessage message = await client.SendAsync(request))
            {
                string data = await message.Content.ReadAsStringAsync();
                if (message.IsSuccessStatusCode)
                {
                    Debug.WriteLine("retrieved access token!");
                    await _navigationService.NavigateAsync($"/{Pages.Master}/{Pages.Nav}/{Pages.Dashboard}");
                }
                else
                {
                    // show error message or something
                }
            }
        }
    }
}

Let’s talk about what is happening above. I am just using the standard REST functions in .NET, but you can use whichever library you want. The most important thing is what we put in the content of the REST call. This must be a url-like string that has the client id, client secret, the code we retrieved from the navigating event and the callback url and then post it up. If we aren’t successful, I am just restarting the process, but it would probably be a good idea to provide some feedback to the user.

If we are successful, we will get some JSON back in the response content that looks like the following:


{
    "token_type": "bearer",
    "expires_in: 3600,
    "refresh_token": "xxxxxxxxxxx",
    "access_token": "xxxxxxxxxxxxxxxxxxxxxxxxx"
}

You will need the access token value for each of your calls to the Forge API. You need to include it in the HTTP header as:

Authorization: Bearer xxxxxxxxxxxxxxxxx

When the token expires, you can use the refresh token to get a new one without having to get the user to authenticate.

On the next post, we will look at how to the token refresh.