Learn how to manually add Microsoft Azure Active Directory common consent to your ASP.NET application so that it can access secured services.
Prerelease content |
---|
The features and APIs documented in this article are in preview and are subject to change. Do not use them in production. |
In this article, you’ll learn how to build a web application hosted on an Azure website that uses the OneDrive for Business API to access secured folders and files.
You can easily set up access to the OneDrive for Business using the Office 365 API Preview Tools for Visual Studio 2013. If you’re not using the tools, you’ll need to manually set up your app in your development environment, register your app with Microsoft Azure Active Directory, write code to handle tokens, and write the code to work with the OneDrive for Business resources. All these steps are described in this article.
Note |
---|
This article covers OneDrive for Business apps, but the same steps apply to apps that access any other secured resource. |
- An Office 365 account. If you don’t have one, you can sign up for an Office 365 developer site.
- Visual Studio 2012 or Visual Studio 2013.
Note The Office 365 API Preview Tools for Visual Studio 2013, which simplify development, are available for Visual Studio 2013 only. - A test account to use in your application.
We also recommend that you familiarize yourself with the Authorization Code Grant Flow. This will help you understand the authentication process that takes place in the background between your application, Azure AD, and the Office 365 resource so that you can better troubleshoot as you develop.
If you’ve already created an account within your Azure tenancy, you can use that account. Otherwise, you will have to create a new organizational user account to use in this sample.
To create an organizational user account
- Go to https://manage.windowsazure.com/.
- Choose the Active Directory icon on the left side in the Azure portal.
- Choose Add a user.
- Fill in the user name.
- Move to the next screen.
- Create a user profile. To do this:
- Enter a first and last name.
- Enter a display name.
- Set the Role to Global Administrator.
- After you set the role you will be asked for an alternate email address. You can enter the email address that you used to create the subscription, or a different one.
- Move to the next screen.
- Choose create.
- A temporary password is generated. You will use this to sign in later. You will have to change it at that time.
- Choose the check mark to finish creating the organizational user account.
The next step is to create the actual app that contains the UI and code needed to work with the OneDrive for Business REST APIs to list the folders and files in the user’s OneDrive.
To create the Visual Studio project
- Open Visual Studio 2013 and create a new ASP.NET Web Application project. Name the application Get_Stats. Choose OK.
- Choose the MVC template and choose the Change Authentication button. Select the Organization Accounts option. This will display additional options for authentication.
- Choose Cloud – Single Organization.
- Specify the domain of your Azure AD tenancy.
- Set the Access Level to Single Sign On, Read directory data.
Under More Options, you will see the App ID URI is set automatically.
- Choose OK to continue. This brings up a dialog box to authenticate.
Note If you receive an invalid domain name error, you might need to implement a workaround by substituting a real domain name, such as *.onmicrosoft.com, from another Azure subscription that you have. When you complete the Visual Studio new project dialog box, Visual Studio creates a temporary app registration entry on the domain that you specify. You can delete that entry later. As part of the workaround, you need to adjust the web.config settings and manually register the web app in the correct Azure AD domain.
- Enter the credentials of the user you created earlier.
- Choose OK to finish creating the new project. Visual Studio will automatically register the new web app in the Azure AD tenant you specified.
- Run the Visual Studio project, and sign on using the test account you created earlier. After the project is running, you can verify that single-sign on is working because the test account user name is displayed in the upper right corner of the web app.
- Log on with your Azure account.
- In the left navigation, choose Active Directory. Your directory will be listed.
- Choose your directory.
- In the top navigation, choose Applications.
- On the Active Directory tab, choose Applications.
- Add a new application in your Office 365 domain (created at Office 365 sign up) by choosing the “ADD” icon at the bottom of the portal screen. This will bring up a dialog box to tell Azure about your application.
- Choose Add an application my organization is developing.
- For the name of the application, enter Get Stats. For the Type, leave Web application and/or Web API. Then choose the arrow to move to step 2.
- For the Sign-On URL, enter the localhost URL from your Get_Stats Visual Studio project. To find the URL:
- Open your project in Visual Studio.
- In Solution Explorer, choose the Get_Status project.
- From the Properties window, copy the SSL URL value.
- Enter an App ID URI. Because the ID must be unique, it’s a good idea to choose a name that is similar to the app name. For example, you can use your Sign-on URL with your app name, such as https://locahost:44044/Get_Stats.
- Choose the checkmark to finish adding the application. You will be notified that the application was added successfully.
- Copy the APP ID URI to the clipboard.
- In your Get_Stats Visual Studio project, open the web.config file.
- Locate the ida:Realm key and paste the APP ID URI for the value.
- Locate the ida:AudienceUri key and paste the same APP ID URI for the value.
- Locate the audienceUris element and paste the same APP ID URI for the add element’s value.
- Locate the wsFederation element, and paste the same APP ID URI for the realm.
- In the Azure Portal, copy the federation metadata document URL to the clipboard.
- In the web.config file, locate the ida:FederationMetadataLocation key, and paste the URL for the value.
- In the Azure Portal, choose the View Endpoints icon at the bottom.
- Copy the WS-Federation Sign-On Endpoint to the clipboard.
- In the web.config file, locate the wsFederation element and paste the endpoint value for the issuer.
- Save your changes and run the project. You will be prompted to sign on. Sign on by using the test account you created earlier. You should see your account user name displayed in the upper right corner of the web app.
To get an application key for your app
- In the Azure Portal, select the Get_Stats application in the directory.
- Choose the Configure command and then locate the keys section.
- In the Select duration drop-down box, choose 1 year.
- Choose Save.
The key value is displayed.
Note This is the only time that the key is displayed. - In Visual Studio, open the Get_Stats project, and open the web.config file.
- Locate the ida:Password element, and paste the key value for the value. Now your project will always send the correct password when it is requested.
- Save all files.
To configure API permissions
- In the Azure Portal, select the Get Status application in the directory.
- From the top navigation, choose Configure. This displays all the configuration properties.
- At the bottom is a web apis section. Notice that your web app has already been granted access to Azure AD.
- Choose Office365 SharePoint Online API.
- Choose Delegated Permissions and select Read items in all site collections.
Note The options activate when you move over them. - Choose Save to save these changes. Your web app will now request these permissions.
You can also manage permissions by using a manifest. You can download your manifest file by choosing Manage Manifest.
Add the GraphHelper project to your solution
To configure the Graph API Helper Library
- Download the Azure AD Graph API Helper Library.
- Copy the C# folder from the Graph API Helper Library to your project folder (i.e. \Projects\Get_Stats\C#.)
- Open the Get_Stats solution in Visual Studio.
- In the Solution Explorer, choose the Get-Stats solution and choose Add Existing Project.
- Go to the C# folder you copied, and open the WindowsAzure.AD.Graph.2013_04_05 folder.
- Select the Microsoft.WindowsAzure.ActiveDirectory.GraphHelper project and choose Open.
- If you are prompted with a security warning about adding the project, choose OK to indicate that you trust the project.
- Choose the Get_Stats project References folder and then choose Add Reference.
- In the Reference Manager dialog box, select Extensions and then select the Microsoft.Data.OData version 5.6.0.0 assembly and the Microsoft.Data.Services.Client version 5.6.0.0 assembly.
- In the same Reference Manager dialog box, expand the Solution menu on the left, and then select the checkbox for the Microsoft.WindowsAzure.ActiveDirectory.GraphHelper.
- Choose OK to add the references to your project.
- Add the following using directives to the top of HomeController.cs.
using Microsoft.WindowsAzure.ActiveDirectory; using Microsoft.WindowsAzure.ActiveDirectory.GraphHelper; using System.Data.Services.Client;
- Save all files.
Add code to manage tokens and requests
Your custom code handles the following scenarios:
- Obtaining an authentication code
- Using the authentication code to obtain an access token and a multiple resource refresh token
- Using the multiple resource refresh token to obtain a new access token for a new workload
To create code to manage tokens and requests
- Open your Visual Studio project for Get_Stats.
- Open the HomeController.cs file.
- Create a new method named Stats by using the following code.
public ActionResult Stats() { var authorizationEndpoint = "https://login.windows.net/"; // The oauth2 endpoint. var resource = "https://graph.windows.net"; // Request access to the AD graph resource. var redirectURI = ""; // The URL where the authorization code is sent on redirect. // Create a request for an authorization code. string authorizationUrl = string.Format("{1}common/oauth2/authorize?&response_type=code&client_id={2}&resource={3}&redirect_uri={4}", authorizationEndpoint, ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value, AppPrincipalId, resource, redirectURI);
- The Stats method constructs a request for an authorization code and sends the request to the Oauth2 endpoint. If successful, the redirect returns to the specified CatchCode URL. Next, create a method to handle the redirect to CatchCode.
public ActionResult CatchCode(string code) {}
- Acquire the access token by using the app credentials and the authorization code. Use your project’s correct port number in the following code.
// Replace the following port with the correct port number from your own project. var appRedirect = "https://localhost:44307/Home/CatchCode"; // Create an authentication context. AuthenticationContext ac = new AuthenticationContext(string.Format("https://login.windows.net/{0}", ClaimsPrincipal.Current.FindFirst(TenantIdClaimType).Value)); // Create a client credential based on the application ID and secret. ClientCredential clcred = new ClientCredential(AppPrincipalId, AppKey); // Use the authorization code to acquire an access token. var arAD = ac.AcquireTokenByAuthorizationCode(code, new Uri(appRedirect), clcred);
- Next use the access token to call the Graph API and get the list of users for the Office 365 tenant. Paste the list into the following code.
// Convert token to the ADToken so you can use it in the graphhelper project. AADJWTToken token = new AADJWTToken(); token.AccessToken = arAD.AccessToken; // Initialize a graphService instance by using the token acquired in the previous step. Microsoft.WindowsAzure.ActiveDirectory.DirectoryDataService graphService = new DirectoryDataService("09f9ea02-9be8-4597-86b9-32935a17723e", token); graphService.BaseUri = new Uri("https://graph.windows.net/09f9ea02-9be8-4597-86b9-32935a17723e"); // Get the list of all users. var users = graphService.users; QueryOperationResponse<Microsoft.WindowsAzure.ActiveDirectory.User> response; response = users.Execute() as QueryOperationResponse<Microsoft.WindowsAzure.ActiveDirectory.User>; List<Microsoft.WindowsAzure.ActiveDirectory.User> userList = response.ToList(); ViewBag.userList = userList;
- Now you need to call Microsoft OneDrive for Business, and this requires a new access token. Verify that the current token is a multiple resource refresh token, and then use it to obtain a new token. Paste the token into the following code.
// You need a new access token for new workload. Check to determine whether you have the MRRT. if (arAD.IsMultipleResourceRefreshToken) { // This is an MRRT so use it to request an access token for SharePoint. AuthenticationResult arSP = ac.AcquireTokenByRefreshToken(arAD.RefreshToken, AppPrincipalId, clcred, "https://imgeeky.spo.com/"); }
- Finally, call Microsoft OneDrive for Business to get a list of files in the Shared with Everyone folder. Paste the list into the following code and replace any placeholders with correct values.
// Now make a call to get a list of all files in a folder. // Replace placeholders in the following string with correct values for your domain and user name. var skyGetAllFilesCommand = "https://YourO365Domain-my.spo.com/personal/YourUserName_YourO365domain_spo_com/_api/web/GetFolderByServerRelativeUrl('/personal/YourUserName_YourO365domain_spo_com/Documents/Shared%20with%20Everyone')/Files"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(skyGetAllFilesCommand); request.Method = "GET"; WebResponse wr = request.GetResponse(); ViewBag.test = wr.ToString(); return View();
- Create a view for the CatchCode method. In Solution Explorer, expand the Views folder and choose Home, and then choose Add View.
- Enter CatchCode as the name of the new view, and choose Add.
- Paste the following HTML to render the users and Microsoft OneDrive for Business response from the CatchCode method.
@{ ViewBag.Title = "CatchCode"; } <h2>Users</h2> <ul id="users"> @foreach (var user in ViewBag.userList) { <li>@user.displayName</li> } </ul> <h2>OneDrive for Business Response</h2> <p>@ViewBag.skyResponse</p>
- Build and run the solution. Verify that you get a list of users, and that you get an XML response from the OneDrive for Business method call. To change the XML response, add files to the OneDrive for Business Share with Everyone folder.