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

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.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.
publ…