Xamarin Forms, Autodesk Forge Access Token

In the previous posts, we went through each platform, looking at how we implement deep linking for each of the platforms. At the end of the deep link flow, we have arrived back within our portable Application object with a URL to process. This URL has a response code at the end that we have to parse out and send back to Forge to get our access and refresh tokens.

This is pretty easy, something like this works:


private string GetResponseCodeFromUrl(string redirectUrl)
{
    string codeParameter = "?code=";
    int pos = redirectUrl.IndexOf(codeParameter);
    string code = redirectUrl.Substring(pos + codeParameter.Length);
    return code;
}

After that we post a REST call to “https://developer.api.autodesk.com/authentication/v1/gettoken”. Inside of the content of the post call, we need to add a string with all of our app keys and codes, in a similar fashion to how we started off the whole authentication process in the first post of the series. The string content looks like this and should be all on one line.

var content = new StringContent($"client_id={ClientId}&client_secret={ClientSecret}&grant_type=authorization_code&code={ResponseCode}&redirect_uri={CallbackUrl}");

See the above link for an explanation of the ClientId, ClientSecret and redirect_uri. The ReponseCode is simply the code that we retrieved using the above GetResponseCodeFromUrl function above.


private AuthData AuthorizationData { get; set; }

public async Task<bool> GetAccessTokenAsync(string redirectUrl)
{
    ResponseCode = GetResponseCodeFromUrl(redirectUrl);
    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={ResponseCode}&redirect_uri={CallbackUrl}");
            request.Content.Headers.ContentType = 
                new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            using (HttpResponseMessage response = await client.SendAsync(request))
            {
                string data = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    AuthorizationData = Deserialize<AuthData>(data);
                    return true;
                }
            }
        }
    }

    return false;
}

If all goes well, we end up getting a response with our authorization data. That structure looks like this:

public class AuthData
{
    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresInMinutes { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }

    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    public DateTime DateGranted { get; set; }

    public AuthData()
    {
        DateGranted = DateTime.Now;
    }
}

I am using Json.NET as my deserializer and am using the attributes to redirect the parsed data into the properties that I want. I think pretty much everyone uses Json.NET, but if it is the first you have heard about it, it is definitely worth your time to look at. Important properties above are:

  • AccessToken: use this for all of your Forge requests so that Forge knows you are authenticated.
  • RefreshToken: the access token will expire. You use the refresh token to request a new one without forcing the user to re-authenticate.
  • ExpiresIn: how many minutes before the access token expires.
  • DateGranted: not returned by Forge, but sets when the token was granted so that we can compute when it expires.
  • And that is about it! In the next post, we will look at refreshing the access token.

Xamarin Forms, Autodesk Forge, iOS Deep-Linking

Alright, last time we looked at UWP, and now we will look at iOS. It is a pretty similar effort to UWP. All we need to do is declare the protocol handling and then handle the URL.

Declaring the Protocol

First we have to edit the info.plist file in the iOS project. This file needs to be modified by hand and is just a simple XML file. The plist element is the root element and contains a “dict” object. Each element of the dict object is a setting for the app and it is contained in pairs. For example:

<plist version="1.0">
<dict>
    <key>UIDeviceFamily</key>
    <array>
        <integer>1</integer>
        <integer>2</integer>
    </array>

    ... other settings
</dict>
</plist>

At the end of the file, we can add our protocol declaration. It will look like this:

<plist version="1.0">
<dict>
    ... other settings

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLName</key>
            <string>same.asyour.bundle.identifier</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>bbsw-fm</string>
            </array>
        </dict>
    </array>
</dict>
</plist>

Handling the URL Link

This is almost exactly like how we did it in the UWP platform project. In the AppDelegate class, we need to override the OpenUrl method and delegate back to the portable Application object.


public partial class AppDelegate : global:Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{

    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        DeepLink.App thisApp = (DeepLink.App) Prism.Unity.PrismApplication.Current;
        thisApp.UwpIOSOnAppLinkRequestReceived(new Uri(url.ToString()));
        return true;
    }
}

All that is happening above is that when the app is activated because of the protocol that it has registered, it will look at the URL and extract the response code that was returned by Forge. It will then use that response code in a REST API call to get the authorization token and refresh token. If that is successful, we perform a navigation to the next page in our app. Obviously the code isn’t complete as it doesn’t handle any kinds of errors. For the details on how to get the authorization and refresh tokens see the previous post.

Next up and finally will be the Android implementation.

Xamarin Forms UWP Deep-Linking

Introduction

In our last post, we looked at what we needed to do to setup our shared/portable project to authenticate with Autodesk Forge. Almost all of the code the important code is in the shared area, but we do have to do somethings within each of the platform projects. Lets check out UWP.

Protocol Declaration

The first thing that I do is go into the Package.appxmanifest in the UWP project. Once you are in it, click on the “Declarations” tab. On this tab, you can declare lots of different things for your app: able to pick files, camera settings, background tasks among others. The one we are interested in is protocol.

Select protocol and add it to the list of the supported declarations. Give the protocol a name check “ExecutableOrStartPageIsRequired”. For the name, make sure that you give it something unique. Perhaps an abbreviation of your company followed by some kind of app designation.

packageappxmanifest

Override UWP Application.OnActivated

In the UWP platform project, you need to override the Application.OnActivated function to handle the deep-link. Normally Xamarin Forms will just route the URI request to OnAppLinkRequestReceived, but it doesn’t seem to be working for UWP (or iOS). So what we will do, is just call in to a new entry point which then delegates to the protected function.


/// UWP application object
sealed partial class App : Application
{
    // ... other stuff here

    protected override async void OnActivated(IActivatedEventArgs args)
    {
        base.OnActivated(args);

        if (args.Kind == ActivationKind.Protocol)
        {
            var protocolArgs = args as ProtocolActivatedEventArgs;
            DeepLink.App thisApp =
                (DeepLink.App) Prism.Unity.PrismApplication.Current;
            thisApp.UwpIOSOnAppLinkRequestReceived(protocolArgs.Uri);
        }
    }
}

Then we can go back to the application object in our portable library and fix up the OnAppLinkRequestReceived function and the manual entry point we show above that is used for UWP and iOS.


public partial class App : PrismApplication
{
    /// the rest of the class is up here ...

    protected override async void OnAppLinkRequestReceived(Uri uri)
    {
        base.OnAppLinkRequestReceived(uri);
        bool retrievedToken = await GetAccessTokenAsync(uri.ToString());
        if (retrievedToken)
            await NavigationService.NavigateAsync(Pages.Test);
    }

    public void UwpIOSOnAppLinkRequestReceived(Uri uri)
    {
        OnAppLinkRequestReceived(uri);
    }

}

All that is happening above is that when the app is activated because of the protocol that it has registered, it will look at the URL and extract the response code that was returned by Forge. It will then use that response code in a REST API call to get the authorization token and refresh token. If that is successful, we perform a navigation to the next page in our app. Obviously the code isn’t complete as it doesn’t handle any kinds of errors. For the details on how to get the authorization and refresh tokens see the previous post.

And that is it for UWP, just a little bit of code and we are back in our shared code base. Up next will be iOS.

Xamarin Forms and Forge Deep Linking

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.

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.