Tuesday, May 12, 2015

Developing ASP.NET application using Active Directory in Azure

Create an ASP.NET Application

The following steps use Visual Studio Express 2013 for Web, and requires Visual Studio 2013 Update 3.
  1. In Visual Studio, click File and then New Project. On the New Project dialog, select the Visual C# Web project from the left menu and click OK. You may also want to uncheck the Add Application Insights to Project if you don't want the functionality for your application.
  2. In the New ASP.NET Project dialog, select MVC, and then click Change Authentication.

  3. On the Change Authentication dialog, select Organizational Accounts. These options can be used to automatically register your application with Azure AD as well as automatically configure your application to integrate with Azure AD. You don't have to use theChange Authentication dialog to register and configure your application, but it makes it much easier. If you are using Visual Studio 2012 for example, you can still manually register the application in the Azure Management Portal and update its configuration to integrate with Azure AD.
    In the drop-down menus, select Cloud - Single Organization and Single Sign On, Read directory data. Enter the domain for your Azure AD directory, for example (in the images below)  aricka0yahoo.onmicrosoft.com, and then click OK. You can get the domain name from the Domains tab for the Default Directory on the azure portal (see the next image down).



    The following image shows the domain name from the Azure portal.



    Note: You can optionally configure the Application ID URI that will be registered in Azure AD by clicking More Options. The App ID URI is the unique identifier for an application, which is registered in Azure AD and used by the application to identify itself when communicating with Azure AD. For more information about the App ID URI and other properties of registered applications, see this topic. By clicking the checkbox below the App ID URI field, you can also choose to overwrite an existing registration in Azure AD that uses the same App ID URI.
  4. After clicking OK, a sign-in dialog will appear, and you'll need to sign in using a Global Administrator account (not the Microsoft account associated with your subscription). If you created a new Administrator account earlier, you'll be required to change the password and then sign in again using the new password.

  5. After you've successfully authenticated, the New ASP.NET Project dialog will show your authentication choice (Organizational ) and the directory where the new application will be registered (aricka0yahoo.onmicrosoft.com in the image below). Below this information, select the checkbox labeled Host in the cloud. If this checkbox is selected, the project will be provisioned as an Azure web app and will be enabled for easy publishing later. Click OK.

  6. The Configure Azure Website dialog will appear, using an auto-generated site name and region. Also note the account you're currently signed into in the dialog. You want to make sure that this account is the one that your Azure subscription is attached to, typically a Microsoft account.
    Note: This project requires a database. You need to select one of your existing databases, or create a new one. A database is required because the project already uses a local database file to store a small amount of authentication configuration data. When you deploy the application to an Azure Website, this database isn't packaged with the deployment, so you need to choose one that's accessible in the cloud. Click OK.

  7. The project will be created, and your authentication options and web app options will be automatically configured with the project. Once this process has completed, run the project locally by pressing ^F5. You will be required to sign in using your organizational account. Provide the username and password for the account you created earlier and click Sign in.

  8. After successful sign in, the ASP.NET site will show that you've authenticated by displaying the username in the top right corner of the page.



    If you get the error:
          Value cannot be null or empty. Parameter name: linkText


    see the debug section at the end of the tutorial.

Basics of the Graph API

The Graph API is the programmatic interface used to perform CRUD and other operations on objects in your Azure AD directory. If you select an Organizational Account option for authentication when creating a new project in Visual Studio 2013, your application will already be configured to call the Graph API. This section briefly shows you how the Graph API works.
  1. In your running application, click on the name of the signed-in user at the top right of the page. This will take you to the User Profile page, which is an action on the Home Controller. You'll notice that the table contains user information about the administrator account you created earlier. This information is stored in your directory, and the Graph API is called to retrieve this information when the page loads.

  2. Go back to Visual Studio and expand the Controllers folder and then open the HomeController.cs file. You'll see a UserProfile() action that contains code to retrieve a token and then call the Graph API. This code is duplicated below:
        [Authorize]
        public async Task UserProfile()
        {
            string tenantId = ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value;
    
            // Get a token for calling the Azure Active Directory Graph
            AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, LoginUrl, tenantId));
            ClientCredential credential = new ClientCredential(AppPrincipalId, AppKey);
            AuthenticationResult assertionCredential = authContext.AcquireToken(GraphUrl, credential);
            string authHeader = assertionCredential.CreateAuthorizationHeader();
            string requestUrl = String.Format(
                CultureInfo.InvariantCulture,
                GraphUserUrl,
                HttpUtility.UrlEncode(tenantId),
                HttpUtility.UrlEncode(User.Identity.Name));
    
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            request.Headers.TryAddWithoutValidation("Authorization", authHeader);
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();
            UserProfile profile = JsonConvert.DeserializeObject<UserProfile>(responseString);
    
            return View(profile);
        }
    To call the Graph API, you first need to retrieve a token. When the token is retrieved, its string value must be appended in the Authorization header for all subsequent requests to the Graph API. Most of the code above handles the details of authenticating to Azure AD to get a token, using the token to make a call to the Graph API, and then transforming the response so that it can be presented in the View.
    The most relevant portion for discussion is the following highlighted line: UserProfile profile = JsonConvert.DeserializeObject<UserProfile>(responseString);. This line represents the name of the user, which has been deserialized from the JSON response and is presented in the View.
    You can call the Graph API using HttpClient and handle the raw data yourself, but an easier way is to use the Graph Client Library which is available via NuGet. The Client Library handles the raw HTTP requests and the transformation of the returned data for you, and makes it much easier to work with the Graph API in a .NET environment. See the related Graph API code samples on GitHub.

No comments:

Post a Comment