in Office 365

Office 365 API Client Libraries – Authenticating your client to Office 365

UPDATE: Office 365 API Tool Summer Update brings breaking changes to the Office 365 API Authentication Library. Please refer to the following post for updated content:

 

Changes to Office 365 API Authentication Library in the Summer Update

Introduction

One of the cool things with today’s Office 365 API Tooling update is that you can now access the Office 365 APIs using libraries available for .NET and JavaScript. These libraries make it easier to interact with the REST APIs from the device or platform of your choice. And when I say platform of your choice, it really is! Office 365 API and the client libraries support the following project types in Visual Studio today:

  1. NET Windows Store Apps
  2. .NET Windows Store Universal Apps
  3. Windows Forms Applications
  4. WPF Applications
  5. ASP.NET MVC Web Applications
  6. ASP.NET Web Forms Applications
  7. Xamarin Android and iOS Applications
  8. Multi-device Hybrid Apps

p.s: support for more projects coming on the way….

Few Things Before We Get Started

  • The authentication library is released as “alpha”.
    • If you don’t see something you want or if you think we missed addressing some scenarios/capabilities, let us know!
    • In this initial release of the authentication library, we focused on simplifying the getting started experience, especially for Office 365 services and not so much on the interoperability across other services (that support OAuth) but that’s something we can start looking for next updates to make it more generic.
  • The library is not meant to replace Active Directory Authentication Library (ADAL) but it is a wrapper over it (where it exists) which gives you a focused getting started experience.
    • However, If you want to opt out and go “DIY”, you still can.

UPDATE: Office 365 API Tool Summer Update brings breaking changes to the Office 365 API Authentication Library. Please refer to the following post for updated content:

 

Changes to Office 365 API Authentication Library in the Summer Update

Setting Up Authentication

The first step to accessing Office 365 APIs via the client library is to get authenticated with Office 365.

Once you configure the required Office 365 service and its permissions, the tool will add the required client libraries for authentication and the service into your project.

Lets quickly look at what authenticating your client looks like.

Getting Authenticated

Office 365 APIs use OAuth Common Consent Framework for authentication and authorization.

Below is the code to authenticate your .NET application:

Authenticator authenticator =  class="kwrd">new Authenticator();

AuthenticationInfo authInfo =
await authenticator.AuthenticateAsync(ExchangeResourceId);

Below is the JS code snippet used for authentication in Cordova projects:

 class="kwrd">var authContext =  class="kwrd">new O365Auth.Context();
authContext.getIdToken( class="str">'https://outlook.office365.com/')
.then(( class="kwrd">function (token) {
     class="kwrd">var client =  class="kwrd">new Exchange.Client( class="str">'https://outlook.office365.com/ews/odata', 
                         token.getAccessTokenFn( class="str">'https://outlook.office365.com'));
    client.me.calendar.events.getEvents().fetch()
        .then( class="kwrd">function (events) {
             class="rem">// get currentPage of events and logout
             class="kwrd">var myevents = events.currentPage;
            authContext.logOut();
        },  class="kwrd">function (reason) {
             class="rem">// handle error
        });
}).bind( class="kwrd">this),  class="kwrd">function (reason) {
     class="rem">// handle error
});  

Authenticator Class

The Authenticator class initializes the key stuff required for authentication:

1) Office 365 app client Id

2) Redirect URI

3) Authentication URI

You can find these settings in:

– For Web Applications – web.config

– For Windows Store Apps – App.xaml

– For Desktop Applications (Windows Forms & WPF) – AssemblyInfo.cs/.vb

– For Xamarin Applications – AssemblyInfo.cs

UPDATE: Office 365 API Tool Summer Update brings breaking changes to the Office 365 API Authentication Library. Please refer to the following post for updated content:

 

Changes to Office 365 API Authentication Library in the Summer Update

If you would like to provide these values at runtime and not from the config files, you can do so by using the alternate constructor:

image

To authenticate, you call the AuthenticateAsync method by passing the service’s resource Id:

AuthenticationInfo authInfo = await authenticator.AuthenticateAsync(ExchangeResourceId);

If you are using the discovery service, you can specify the capability instead of the resource Id:

AuthenticationInfo authInfo =
await authenticator.AuthenticateAsync( class="str">"Mail", ServiceIdentifierKind.Capability);

The string to use for other services if you use discovery service: Calendar, Contacts and MyFiles

NOTE:

– For now, if you want to use the discovery service, you will also need to configure a SharePoint resource, either Sites or My Files. This is because the discovery service currently uses SharePoint resource Id.

– Active Directory Graph & Sites do not support discovery service yet

Depending on your client, the AuthenticateAsync will open the appropriate window for you to authenticate:

– For web applications, you will be redirected to login page to authenticate

– For Windows Store Apps, you will get dialog box to authenticate

– For desktop apps, you will get a dialog window to authenticate

image

AuthenticatorInfo Class

Once successfully authenticated, the method returns an AuthenticatorInfo object which helps you to get the required access token:

ExchangeClient client =
 class="kwrd">new ExchangeClient( class="kwrd">new Uri(ExchangeServiceRoot), authInfo.GetAccessToken);

 

And also help you re-authenticate for a different resource when you create the service client.

AuthenticationInfo graphAuthInfo =
    await authInfo.ReauthenticateAsync( class="str">"https://graph.windows.net/");

The library automatically handles token lifetime management by monitoring the expiration time of the access token and performing a refresh automatically.

Thats it! – Now you can make subsequent calls to the service to return the items you want!

Authentication Library

For .NET projects:

The library is available as a Nuget package. So, if you want to add it manually to your project without the tool, you could do so. However, you will have to manually register an app in the Azure Active Directory to authenticate against AAD.

Microsoft Office 365 Authentication Library for ASP.NET

Microsoft Office 365 Authentication Library for .NET (Android and iOS)

Microsoft Office 365 Authentication Library for ASP.NET

For Cordova projects:

You will need to use the Office 365 API tool which generates the aadgraph.js under the Scripts folder that handles authentication.

Let us know what you think and join the conversation!

UPDATE: Office 365 API Tool Summer Update brings breaking changes to the Office 365 API Authentication Library. Please refer to the following post for updated content:

 

Changes to Office 365 API Authentication Library in the Summer Update

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.

  1. Great writing,

    I think you’ve to point to the fact that devs have to change the “App Properties” in the Add Connected Service dialog to “Multiple Organizations” as soon as they like to allow each O365 user to log in and use the data sitting in their own tenants.

    Really looking forward to see the JS side packed as Nuget Package and you should review bower.io you have to publish it also over there. Open Source Community is relying more on bower.io instead of nuget 🙂

    Thorsten

  2. Great article,

    I have to create a web form application which displays different resources from O365Api, but if I try to reauthenticate I get an error:
    for example for this code:
    Authenticator authenticator = new Authenticator();
    var auth = await authenticator.AuthenticateAsync(“Mail”, ServiceIdentifierKind.Capability);
    var graphAuthInfo = await auth.ReauthenticateAsync(“https://graph.windows.net/”);

    I get an ArgumentNullException:
    Value cannot be null.
    Parameter name: uriString

    Please let me know if you run into this before or if I do something wrong.

    Thanks!

  3. Great Article,
    Can you please provide sample to connect with office 365 using Win Form application.
    Right now i am not able to connect it with.
    “Application with Identifier is not registerd ” error which i am getting during running process.

    Application is added into azure directory.
    any help will be appreciated.