Skip to main content

Azure Active Directory - How to get access token for Office 365 from a native application (SL,WPF, Store)

In the last post we talked a little about Azure Active Directory (AAD) and we discover what are the main features. Today, we will see how we can get an authentication token from AAD of Office 365 and use it from a native application.
When we are talking authentication and tokens around AAD for native application we need to know two important things.
The first thing is around Microsoft Azure portal, where you will need to create a native application for AAD and give the specific rights.  For more information related to this topic see the last post.
The second thing is related to the code that we need to write to be able to authenticate and get the token. For different platforms like Silverlight, WPF or Store application Microsoft already delivered a NuGet package that can be used to generate and use the token. The name of the NuGet package is “Active Directory Authentication Library”.
Once you added this package to your project, you will need to create an instance of AuthenticationContext and specify the resources that you want to access, client id and redirect URL.
The token that will be generated can be used only for that specific resources. Don’t forget to give access to you application from Active Directory section of Azure portal to that specific resource. The client id and redirect URL can be obtained from Azure portal.
Hint: Redirect URL needs to be the same as you specified on the portal.
AuthenticationContext authenticationContext = 
  new AuthenticationContext(_loginUrl);
AuthenticationResult result = authenticationContext.AcquireToken(
  "https://outlook.office365.com/", //This is resource id for Exchange Server from Office 365
  "clientID",
  new Uri("http://localhost/"));
string myCoolToken = result.AccessToken;
When the above method is called, a window will be displayed to the user. In this form, the user will have to enter his credentials (email and password). At this step you don’t have any control to the window, you cannot prefilled it, change the UI and so on. This is fully controlled by the credentials provider (in our case Microsoft).
In the end this is a good think, because the user knows that the application cannot access his private information like password.
In the authentication ends with success, the result of the call will be the token itself and other information related to it. In the result we can find the following information

  • Access token – that can be used to access the specific resources
  • Refresh token – that can be used to refresh the access token without requiring the user to enter his credentials
  • Tenant Id – the id of the tenant (resources) that can be accessed using the access token
  • User information – information related to the user (name, user id, identify provider)
  • Expiration date – the date when the access token will expire

Keep in mind that the authentication is done using Internet Explorer cached data. Because of this, if you are already login on IE with a specific user, you should sign out or clear IE cache. I recommend the second thing, is safer and you can save a lot of time – trust me.
Based on the resource (tenant) that you want to access, you will use the token in different ways. In our case, to access the email inbox of the user, you can use the token directly to EWS Library, without having to specify the user email address – SO COOL
ExchangeService exchangeService = new ExchangeService();
exchangeService.Credentials = 
  new OAuthCredentials(myCoolToken);
exchangeService.Url = 
  new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
In this post we saw we can get an access token from a native application. In the next post we will see how we can do this in a non-native application like web or Windows Phone (yes, we don’t have YET, a native library for Windows Phone).

Comments

  1. Nice post! I am working on same thing and need to hardcode username and password. From your writing and after going though AuthenticationContext object it seems, automating that is not possible? Am I missing something here?
    Thanks,
    Vinay Kumar.

    ReplyDelete
    Replies
    1. After user login, you can access user information. I will come later this day with a post.

      Delete
    2. Hmm, that seems genuine. I am looking for authenticating azure portal with hardcoding username and password through AAD.

      Delete

Post a Comment

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...