Monthly Archives: February 2015

Use ADAL for iOS/OSX with O365 Discovery REST API

You want to access your Office 365 data from an iOS / OSX application and don’t know how to start ? You are in the right place 😉

In this article, we will see the first step to write an application connected to Office 365 which consists to discover what services are available for the current user and what are the endpoints URLs for each.

When you want to connect to Office 365 from an application and use the REST API to retrieve data, you need to authenticate against Azure Active Directory (each user accounts are stored in AAD).

To help us to achieve this goal, Microsoft has released a library named ADAL (Active Directory Azure Library) which was written in Objective-C and can be used with iOS and OSX.

You can download ADAL for free on GitHub : https://github.com/AzureAD/azure-activedirectory-library-for-objc

The next step to be able to write an application which operates with Office 365 is to declare it in the Azure directory associated to your Office 365 tenant. If you are a global administrator of your tenant, you can achieve this by using the Azure Management Portal : https://manage.windowsazure.com

On the Azure Management Portal, go to Active Directory section, select the appropriate directory, select applications and create a new native application.

After you fill the requested information (a name and a redirect URL), you have to declare for each service (SharePoint, Exchange, Active Directory…) what permissions are needed by your application as you can see below.

Azure Manage Portal - Application Permissions

We are now ready to write code to connect to Office 365 and to discover what services are available for our user account.

In your application (it works in the same way for iOS and OSX), add the ADAL library in your project as usual when you use a third party library/framework.

    NSString *clientId = @"12345678-abcd-1234-abcd-1234567890ab";
    NSURL *redirectUri = [NSURL URLWithString:@"https://beecomedigitaldemo"];

    ADAuthenticationContext *authenticationContext = [ADAuthenticationContext authenticationContextWithAuthority:@"https://login.windows.net/common" error:nil];
    [authenticationContext acquireTokenWithResource:@"https://api.office.com/discovery/" clientId:clientId redirectUri:redirectUri completionBlock:^(ADAuthenticationResult *result) {
        if (result.status == AD_SUCCEEDED) {
            // Authentication succeeded
        }
        else if (result.status == AD_USER_CANCELLED) {
            // Authentication cancelled by the user
        }
        else {
            // Authentication failed
        }
    }];

To authenticate against Azure Active Directory, we have to use the ADAuthenticationContext class available in ADAL.

To instanciate a context, you need to indicate what is the authentication authority you will use. The default authority to logon with Azure Active Directory is https://login.windows.net/common but if it’s applicable for your company, you can specify another authority.

After the instanciation of the context, you have to acquire an authentication token for the resource which you will request later.

In our case, we want to discover services offered by Office 365. The resource associated is https://api.office.com/discovery/ (be careful to not omit the trailing slash character in the URL otherwise it will not work).

When you want to get a token by calling the acquireTokenWithResource method, you have to set a clientId and a redirectUri. These values are those you have declared in the Azure Management Portal.

This method executes asynchronously so when it’s finished, the completionBlock passed in the last parameter is executed. To ensure that the request was successfull, you can test the result status. If everything was good, status will be equal to AD_SUCCEED. Otherwise it will be equal to AD_FAILED or AD_USER_CANCELLED.

Now that we are successfully authenticated and we have a valid authentication token, we can discover what services are available. To do it, we just have to send a request to the discovery REST API endpoint.

// In-house wrapper of NSURLSession to simplify HTTP communications
BCDHttpClient *httpClient = [[BCDHttpClient alloc] init];

NSURL *serviceURL = [NSURL URLWithString:@"https://api.office.com/discovery/v1.0/me/services"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serviceURL];
[request setValue:[NSString stringWithFormat:@"Bearer %@", result.accessToken] forHTTPHeaderField:@"Authorization"];

[httpClient dataWithRequest:request completionHandler:^(NSHTTPURLResponse *response, NSData *data, NSError *error) {
    if (error == nil) {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@", jsonObject);
    }
}];

As you can see above, we build a NSMutableURLRequest with the URL of the Office 365 discovery endpoint : https://api.office.com/discovery/v1.0/me/services

To call this endpoint and retrieve information associated to our user profile, we need to add an Authorization HTTP header with the following format : “Bearer our_access_token“.

The access token is the one that have been retrieved by ADAL and is accessible in the result parameter of the completion block.

Then we execute the request by using our in-house implementation of a HTTP client (just a lightweight wrapper around NSURLSession). If the request complete successfully, we deserialize the retrieved data (in JSON format) and print them in the console.

You can see below the result printed in our console for all services found for the current authenticated user. In this example, our user have access to SharePoint and Exchange with many different services for each (MyFiles, RootSite, Calendar, Contacts and Mail).

{
    "@odata.context" = "https://api.office.com/discovery/v1.0/me/$metadata#allServices";
    value =     (
                {
            "@odata.editLink" = "services('MyFiles@O365_SHAREPOINT')";
            "@odata.id" = "https://api.office.com/discovery/v1.0/me/services('MyFiles@O365_SHAREPOINT')";
            "@odata.type" = "#Microsoft.DiscoveryServices.ServiceInfo";
            capability = MyFiles;
            entityKey = "MyFiles@O365_SHAREPOINT";
            providerId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            providerName = Microsoft;
            serviceAccountType = 2;
            serviceApiVersion = "v1.0";
            serviceEndpointUri = "https://beecomedigitaldemo-my.sharepoint.com/_api/v1.0/me";
            serviceId = "O365_SHAREPOINT";
            serviceName = "Office 365 SharePoint";
            serviceResourceId = "https://beecomedigitaldemo-my.sharepoint.com/";
        },
                {
            "@odata.editLink" = "services('RootSite@O365_SHAREPOINT')";
            "@odata.id" = "https://api.office.com/discovery/v1.0/me/services('RootSite@O365_SHAREPOINT')";
            "@odata.type" = "#Microsoft.DiscoveryServices.ServiceInfo";
            capability = RootSite;
            entityKey = "RootSite@O365_SHAREPOINT";
            providerId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            providerName = Microsoft;
            serviceAccountType = 2;
            serviceApiVersion = "v1.0";
            serviceEndpointUri = "https://beecomedigitaldemo.sharepoint.com/_api";
            serviceId = "O365_SHAREPOINT";
            serviceName = "Office 365 SharePoint";
            serviceResourceId = "https://beecomedigitaldemo.sharepoint.com/";
        },
                {
            "@odata.editLink" = "services('Contacts@O365_EXCHANGE')";
            "@odata.id" = "https://api.office.com/discovery/v1.0/me/services('Contacts@O365_EXCHANGE')";
            "@odata.type" = "#Microsoft.DiscoveryServices.ServiceInfo";
            capability = Contacts;
            entityKey = "Contacts@O365_EXCHANGE";
            providerId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            providerName = Microsoft;
            serviceAccountType = 2;
            serviceApiVersion = "v1.0";
            serviceEndpointUri = "https://outlook.office365.com/api/v1.0";
            serviceId = "O365_EXCHANGE";
            serviceName = "Office 365 Exchange";
            serviceResourceId = "https://outlook.office365.com/";
        },
                {
            "@odata.editLink" = "services('Mail@O365_EXCHANGE')";
            "@odata.id" = "https://api.office.com/discovery/v1.0/me/services('Mail@O365_EXCHANGE')";
            "@odata.type" = "#Microsoft.DiscoveryServices.ServiceInfo";
            capability = Mail;
            entityKey = "Mail@O365_EXCHANGE";
            providerId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            providerName = Microsoft;
            serviceAccountType = 2;
            serviceApiVersion = "v1.0";
            serviceEndpointUri = "https://outlook.office365.com/api/v1.0";
            serviceId = "O365_EXCHANGE";
            serviceName = "Office 365 Exchange";
            serviceResourceId = "https://outlook.office365.com/";
        },
                {
            "@odata.editLink" = "services('Calendar@O365_EXCHANGE')";
            "@odata.id" = "https://api.office.com/discovery/v1.0/me/services('Calendar@O365_EXCHANGE')";
            "@odata.type" = "#Microsoft.DiscoveryServices.ServiceInfo";
            capability = Calendar;
            entityKey = "Calendar@O365_EXCHANGE";
            providerId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            providerName = Microsoft;
            serviceAccountType = 2;
            serviceApiVersion = "v1.0";
            serviceEndpointUri = "https://outlook.office365.com/api/v1.0";
            serviceId = "O365_EXCHANGE";
            serviceName = "Office 365 Exchange";
            serviceResourceId = "https://outlook.office365.com/";
        }
    );
}

As mentioned before, we have to declare what permissions are needed by our application. But what happens exactly for the user if he’s not agree with these permissions ?

When ADAL tries to acquire an access token and if the user account is not stored in the same directory as your tenant, he must consent to authorize the application for the permissions you are requested.

ADAL - User ConsentIf the user doesn’t consent to authorize your application to use the required permissions, ADAL returns an AD_FAILED status when you call acquireTokenWithResource. The consent is required only once. For subsequent requests the same consent is used by ADAL.

Now you are theorically able to use ADAL and Office 365 Discovery REST API to authenticate and retrieve information about available services for the current user  😉

Opening a document with Office Mobile from your own application

You want to write your own mobile application and need to open Office documents from it ?

Since Microsoft has released Office Mobile on iOS and Android platforms, you probably asked how to open Office documents with these applications from your own application.

After few hours of searches on Google, I didn’t find any information on this subject. So I decided to investigate by myself and I found the solution by using Office Web Apps and by analysing how it works when you click on the option “Edit in Word“.

Office Mobile applications expose some special schemes (like http or https) which allow you to open documents and passing information to the application.

Here is the list of schemes I found through my analysis of Office Web Apps :

  • ms-word
  • ms-excel
  • ms-powerpoint
  • onenote

My need is to open in Office Mobile, some documents which are stored in Office 365, but are presented through a dedicated mobile interface (running on iOS). Opening these files with Office Mobile allow users to read and edit them, and save modifications directly to Office 365.

By using previous schemes, it’s easy to build an URL and to open it using the following code :

NSURL *documentURL = [NSURL URLWithString:@"ms-word:https://tenant.sharepoint.com/Shared%20Documents/Document.docx"];
if ([[UIApplication sharedApplication] canOpenURL:documentURL]) {
    [[UIApplication sharedApplication] openURL:documentURL];
}

As you can see, you just have to concatenate the desired scheme (ms-word: in my case) with the URL of the document.

To ensure that Office Mobile is installed on the device, you can check if the application is able to open it with the call to canOpenURL.

When your application execute the openURL method, the right application is executed and the document is opened. If you’re not authenticated inside the application, you’re invited to do it.

Office Mobile - View Mode

When the document was opened, you probably noticed that it was opened in read-only mode.

It’s the default mode, when you just concatenate an URL to the scheme. But what to do if you want to open the document in edit mode ?

I also found the solution by analysing Office Web Apps  😉

You can specify some additional information between the scheme and the URL of the document.

NSURL *documentURL = [NSURL URLWithString:@"ms-word:ofe%7Cu%7Chttps://tenant.sharepoint.com/Shared%20Documents/Document.docx"]

As you can see above, “ofe%7Cu%7C” was inserted to tell Office Mobile that you want to edit the file (I guess “ofe” means “open for edit”). It’s also possible to use “ofv” (I guess it means “open for view”) in the same manner.

When you run the same code as previously, but with the new URL, the yellow bar below the ribbon has disappeared and you can edit the document without any further action.

Office Mobile - Edit mode

Note that after some tests, this also works with Office for Mac (and probably with Office for Windows).

Enjoy  😉