Microsoft have provided Graph APIs as single endpoint to access all type of resources for a Microsoft/Office 365 account. To use Microsoft Graph APIs in a mobile, we can either:

  • REST API: Sending http message to Graph endpoint.
  • Using mobile SDK to simplified the process.

In this article, I will describe the step to use Graph APIs on mobile application using Xamarin Forms.

For a starter, this will take quite a few steps for configuration. But when get used to it, it is really easy process.

For demonstration purpose, let say we need to create a mobile application that fetching calendar items from user’s data.

 

I.   Environment

  1. An Office 365 business account with global administrator privileges.
  2. An Azure subscription.
  3. Visual Studio 2017 Professional with Xamarin installed.

Notes:

  • Office 365 Enterprise E3 provides free trial in 30 days.
  • Azure also provides a free subscription with $200 credit.
  • With the paid Office 365 account, you also have access to its Azure AD.
  • When install VS2017, install “Mobile development with .NET” workloads to install Xamarin SDK, Android SDK… components

 

II.   Configuration

Associate Azure subscription with Office 365 account.

  1. Login to Azure Management Portal (https://manage.windowsazure.com) with Microsoft account with an Azure subscription. This is old portal of Azure services.
  2. On the banner, choose New -> App Services -> Active Directory -> Directory -> Custom Create
  3. Choose Use Existing Directory, check I am ready to be signed out to back to login page.
  4. Login with Office 365 admin account. Choose continue & sign out again.
  5. Close the browser, open again and login to Azure Management Portal. Now the Active Directory associated with Office 365 account is created.

Azure Management Portal (this is the old portal; some Azure services will be available only on new portal.azure.com after 11/2017).

Create an application in Application Registration Portal.

  1. Login to https://apps.dev.microsoft.com/ using Office 365 account.
  2. Choose “Add an app”, define the app name and hit Create.
  3. On the next page, application id will be generated. This is an unique serial number that will define the application on Azure cloud.
  4. Add a platform, in this case, we are going to develop mobile app, so add Native Application platform.
  5. A custom redirect URI is created, it has the form of msalApplicationId://auth, this URI will be used for app authentication later.
  6. Next, we should change the Microsoft Graph permission for the app. Depend on the purpose of the app, please choose the appropriate permission. For more information about permission, please refer to my previous article. For this sample app, we should choose User.Read, Calendars.Read, Calendars.Read.Shared.
  7. Change some other options for the app: change app name, generate password (application secret), …
  8. Finally, click the save button.

Now, we ready to develop a mobile application using Microsoft Graph APIs.

 

III.   Working with Graph APIs on Xamarin Forms

Create Cross-platform App solution & using Xamarin Forms. We will support for Android & iOS platform. So UWP project can be ignored.

 

  1. Install required libraries for Xamarin project

Although we can work with Microsoft Graph APIs perfectly fine using REST methods to communicate with Graph endpoint, it is more convenient to let the libraries do it for us.

Go to NuGet Package Manager and install:

  • Microsoft.Graph.Core
  • Microsoft.Graph
  •  
    Before using Graph, we need to authenticate with the server using Azure AD. To do so, install additional library:

  • Microsoft.Identity.Client
  •  
    Note: as of 11/2017, it seems Microsoft Authentication Library (MSAL), Microsoft.Identity.Client package is not very in active development. The last version (v1.1.0-preview) is from 6 months ago. If you want another up-to-date library, please try to use the nightly build instead. Or switch to Active Directory Authentication Library (ADAL), Microsoft.IdentityModel.Clients.ActiveDirectory package.

     

    If using MSAL 1.1.0-preview, on Xamarin Android project, all the Xamarin.Android.Support.* packages must be at version 23.3.0. Updating to later version 24.* or 25.* with encounter crash when authenticate with CustomTabs related error.

     

    1. Authenticating with Azure AD using MSAL

    After install the package, we need to configure the Android & iOS project so we can receive the redirected response from the web view custom tabs.

    On Android project:

    Open .\Properties\AndroidManifest.xml and add to <application> element:

    <application>
        <activity android:name="microsoft.identity.client.BrowserTabActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="msal{Application ID}" android:host="auth" />
            </intent-filter>
        </activity>
    </application>
    

    For {Application ID}, fill in the actual Id generated in Application Registration Portal.

    Implement the receiving method in MainActivity.cs:

    protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(requestCode, resultCode, data);
    }
    

    On Android, we also need to add:

    UIParentObject = new UIParent(Xamarin.Forms.Forms.Context as Activity);
    

    to get the current activity of Android app.

    On iOS project:

    Open .\info.plist and add the key:

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>{Bunder Indentifier}</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>msala{Application Id}</string>
            </array>
        </dict>
    </array>
    

    For {Bunder Indentifier}, fill in the app identifier of your choice.

    Afterward, implement following method on AppDelegate.cs

    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs(url);
        return true;
    }
    

    The setup for native project is done. On shared project we should declare a PublicClientApplication object.

    It should be something like this:

    PublicClientApplication pcaObject { get; set; }
    ...
    pcaObject = new PublicClientApplication({Application Id});
    pcaObject.RedirectUri = ({Redirect Uri};
    

    Both {Application Id} and {Redirect Uri} is created on Application Registration Portal.

    Now, each time in the application flow, if there is a need for authentication, calling the following method:

    string[] GraphScopes = {"User.Read", "Calendars.Read", "Calendars.Read.Shared"};
    AuthenticationResult authResult = await pcaObject.AcquireTokenAsync(GraphScopes, UiParentObject);
    

    If successful, an AccessToken will be returned in authResult.

    We can use this token to access our Graph APIs, but limited to the permitted scopes: “User.Read”, “Calendars.Read”, “Calendars.Read.Shared”.
     

    1. Using Graph library to acquire user data

    First, we need to get a Graph client using obtained AccessToken above:

    string baseUrl = "https://graph.microsoft.com/v1.0";
    GraphServiceClient graphClient = new GraphServiceClient
    (
        baseUrl,
        new DelegateAuthenticationProvider
        (
            async (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", AccessToken);
            }
        )
    );
    

    From now on, getting user data is easy, just by using API call from library.

    For example, getting loggined user profile:

    var _curUser = await graphClient.Me.Request().GetAsync();
    

    Getting calendar list as one user can have many calendars:

    var _calendarList = await graphClient.Me.Calendars.Request().GetAsync();
    

    Getting events from one particular calendar:

    var _eventList = await graphClient.Me.Calendars[calendarID].Events.Request().GetAsync();
    

    We acquired the calendar items from user data, display it on Xamarin Forms by the desired UI.

    Graph APIs provide much more data other than just calendar. Explore more about their usage first by trying:
    https://developer.microsoft.com/en-us/graph/graph-explorer/

    I will create a sample project later to demonstrate this article.

    Leave a Reply

    メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

    You may use these HTML tags and attributes:

    <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>