Friday, December 13, 2013

Integration testing Azure Active Directory

This post is my history of how I got from not knowing how Azure Active Directory (AAD) to write some integrations tests with MSTest


Last week I had to investigate if Azure Active Directory was an option for my company’s next Web project and future applications. I started to play around inside the Azure Portal to see how that works, and must say that was very intuitive and easy to use- so I won’t cover that in this post.

Now that I had the fundamental understanding on how the AAD worked in the Azure Portal I needed to figure out how I could work with the data through code. I asked Magnus Mårtensson  aka @noopman on twitter (who is Windows Azure MVP) what frameworks to use, and he suggested that I should look at the Windows Azure AD Graph API. The API helps developers execute create, read, update, and delete (CRUD) operations on Windows Azure AD objects such as users and groups. Just the thing I need!

I thought that I could download the files via Nuget, but I wasn’t able to find it, and after some googling I found and MVC Sample App for Windows Azure Active Directory Graph the solution also included the WindowsAzure.AD.Graph project.

This was pretty cool, I could browse through all the code and understand how it all fits together. But why are example code often presented using a web or windows application? Why not just cut of all that web/windows crap and presented the code in small unit tests? This way you can easer understand what it takes to do a specific task with an API.

Prequisites you need to know how to setup an application in AAD if not got here http://msdn.microsoft.com/en-us/library/windowsazure/dn151791.aspx


Enough talking let’s make the tests happens!

Step1

Create a unit test project, in this example I’m using MSTest. Make references to the following dll’s (the dll’s can be found in the WindowsAzure.AD.Graph project)
  • Microsoft.Data.Services.Client.dll
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll
  • Microsoft.WindowsAzure.ActiveDirectory.GraphHelper.2013_04_05.dll


Step2

Be sure that your application Azure Directory Access need to be SINGLE SING-ON, READ AND WRITE DIRECTORY DATA
First Create a GraphServiceHelper class, in this code you have need to specify the
tenantName: example ronniestestaccount.onmicrosoft.com


ClientId and Password
The clientID and password you can find in AAD under the applications “Enable your app to read or write directory data”
public static class GraphServiceHelper
{
        public static DirectoryDataService Create()
        {
            var tenantName = " ronniestestaccount.onmicrosoft.com";
            // retrieve the clientId and password values
            string clientId = "XXXXXXXX-XXX-XXX-XXX-XXXXXXXXXXXX";
            string password = "v4J4p5gHnUeb437Mu4fzLP7e9Oo529ycpE3CNbA104g=";
            // get a token using the helper
            AADJWTToken token = DirectoryDataServiceAuthorizationHelper.GetAuthorizationToken(tenantName, clientId, password);
            // initialize a graphService instance using the token acquired from previous step
            var graphService = new DirectoryDataService(tenantName, token);
            return graphService;
        }
    }


Step3

Now were ready to write some tests, to get started and make sure that you have connection to your AAD write a simple test that get all the users that exist in you AAD. (In my case I have created a few users, so I know that I have more than 2 users in the AAD)

Test1

private DirectoryDataService DirectoryService{
      get { return GraphServiceHelper.Create(); }
}


[TestMethod]
public void ShouldHaveMoreThanTwoUsersInAAD()
{
            var users = DirectoryService.users;
            Assert.IsTrue((users.ToArray().Length >= 3));
}

When this test works, let’s try to create a new user.

Test2

[TestMethod]
public void CanCreateUser()
{
                             DirectoryDataService dataService = DirectoryService;
                             string alias = Guid.NewGuid().ToString();
                             User user = new User();
                             user.displayName = alias;
                             user.userPrincipalName = alias + "@ronniestestaccount.onmicrosoft.com";
                             user.mailNickname = alias;
                             user.passwordProfile = new PasswordProfile{

                                                                                                       forceChangePasswordNextLogin = false, 
                                                                                                       password = "Myy%1982"
                                                                                                };
                             user.accountEnabled = true;
                             dataService.AddTousers(user);
                             dataService.SaveChanges();
                             User newUser = DirectoryService.users
                                                          .Where(usr => usr.userPrincipalName == alias + " @ronniehhegelundgmail.onmicrosoft.com")
                                                          .FirstOrDefault();  
Assert.IsNotNull(newUser);
}

Run the test and got to see the success and go to you AAD to verify it.
Now that we have created a user let’s update the userprofile, by Finding the UserPrincipal of you newly created user in the AAD, and use that instead of the USERPRINCIPAL in the following code example.

Test3

[TestMethod]
public void CanUpdateUserDepartmentName()
{
                             DirectoryDataService dataService = DirectoryService;   
                             User user = dataService.users.Where(it => (it.userPrincipalName == USERPRINCIPAL)).SingleOrDefault();
                             string departmentName = "IT Department_" + DateTime.Now;
                             user.department = departmentName;
                             dataService.UpdateObject(user);
                             dataService.SaveChanges(SaveChangesOptions.PatchOnUpdate);                
                             User newUser = DirectoryService.users
                                                          .Where(it => (it.userPrincipalName == USERPRINCIPAL))
                                                          .SingleOrDefault();
                             Assert.AreEqual(newUser.department, departmentName);
}

 

Summary

In this post I just showed how easy it is to write integrations test against the AAD. And a more lightweight way to try working and debugging the API, than through a MVC application.


2 comments:

  1. Hello Ronnie,
    The Article on Integration testing Azure Active Directory, gives detailed information about it. Thanks for Sharing the information about the Unit Testing For More information check the detail on the Unit Testing here Mobile App Testing

    ReplyDelete
  2. I have read this post. collection of post is a nice one Azure Online Training

    ReplyDelete