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(

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provided a too