Note that the APIs, tools and methods change quickly in this area, this blog post will get old and die eventually…
Many organizations now look at the Azure environment to host their websites and web APIs, and some decide to move their mail and Active Directory too. Now with the latest updates and previews in Azure, you’re able to secure your web APIs with Azure AD. Vittorio Bertocci wrote an article for MSDN Magazine about Secure ASP.NET Web API with Windows Azure AD and Microsoft OWIN Components and it worked fine up until a couple of weeks ago when things moved around in these parts of Azure
I will try to describe in detail how to secure your web API with Azure Active Directory now, using Visual Studio 2013 and the preview of ADAL (Active Directory Authentication Library) package.
Create a web API project
Fire up Visual Studio and create a new ASP.NET Web Application. I’m calling mine “johandanforth”, I’m selecting “Web API” and click the “Change Authentication”
In the next dialog, click “Organizational Account” and enter the domain of your Azure AD tenant, in my case it’s “irm.se”:
After you press “OK” you’ll be asked to login with your Azure AD account, then “OK” again and Visual Studio will create a web application resource in your Azure AD. Now look it up in the Azure Management application. Note that you may have to log out and in again or restart the Azure management web app to see the newly created application.
In my case the application has been named “johandanforth” and is for securing your development project on localhost. The SIGN-ON URL (also called the APP URL in the management application) is https://localhost:44310/ which can be seen both on the applications overview and if you click on the application and go to the CONFIGURE “tab”:
The sign-on url should be the same as where the web API is hosted, in this case the same localhost-settings as you got in the development project web-settings.
Open up web.config of your web API project and have a look at these settings:
<add key="ida:Audience" value="https://irm.se/johandanforth" /> <add key="ida:ClientID" value="d169beb7-34bc-441b-8b93-87e3181a1132" />
The “ida:Audience” in web.config correspond to the value of APP ID URI of the application resource in the management portal and the “ida:ClientID” correspond to the CLIENT ID in the portal.
Update the web application manifest
Before you any application can access this resource, we must update the “manifest”. Still on the CONFIGURE tab for your web API resource, there should be a MANAGE MANIFEST menu option down at the bottom toolbar. Click it and select “Download Manifest”. It’s a json-text-file, and should save it somewhere where you know is, because we will add a section to it and then upload it again using the same menu option:
Open the json-manifest and replace the "appPermissions": , section with this:
"description":"Allow the application full access to the service on behalf of the signed-in user",
"displayName":"Have full access to the service",
"userConsentDescription":"Allow the application full access to the service on your behalf",
"userConsentDisplayName":"Have full access to the service"
Create a client
Now let’s try and access the sample ValuesController Web API in your development environment using a web browser, Fiddler or similar. In my case it’s https://localhost:44309/api/values and you should get a HTTP/1.1 401 Unauthorized error back. To be able to access the protected resource, you must add a client resource in the AD and configure it to access the web API.
If you are not there already, in the Azure management portal, go to Active Directory, click on your domain name and select the APPLICATIONS tab. Then click the ADD-icon down the center of the bottom toolbar. Then go ahead and select “Add an application my organization is developing”:
Enter a name for your client (I’m going with “johandanforth-client”, and make sure you select NATIVE CLIENT APPLICATION because we’re going to write a simple Windows WPF client to call our web API:
On the second page, type in a redirect url for your client – it can be anything as long as it is a valid url. I’m going with https://irm.se/johandanforth-client.
Your client is now created, but the last step to do is to give permission to our web API. Scroll down to the bottom of the client application CONFIGURE page and look at the “permissions to other applications (preview)” section. In the dropdown marked “select application” you should be able to see and select your web API. You must also select the “Delegated permissions” dropdown and mark the only option available for you. As you can see, the description matches the text in the manifest file:
Remember to SAVE!
Almost there, hang on…
Create a Windows WPF application for testing
Add a new Windows WPF Application to your solution, I’m calling it “johandanforth.client”, and create a button with a click-event or something to hold the code that will authenticate and get values from your API. Bring up NuGet and search for “ADAL”, make sure you have “Include Prerelease” selected:
Install the prerelease package from February 2014 (it will probably be updated soon), then paste this code into the click-event of that button you created earlier:
public partial class MainWindow : Window
private async void Button_Click(object sender, RoutedEventArgs e)
//this is to accept dev certificates - do not use in production!
System.Net.ServicePointManager.ServerCertificateValidationCallback = ((a, b, c, d) => true);
var ac = new AuthenticationContext("https://login.windows.net/irm.se"); //ad domain = irm.se
var ar1 = ac.AcquireToken("https://irm.se/johandanforth", //app id uri of the web api
"91b4bc31-92c2-4699-86f5-fa84a718da30", //the client id
new Uri("https://irm.se/johandanforth-client")); //the client redirect uri
var authHeader = ar1.CreateAuthorizationHeader();
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44310/api/values");
var response = await client.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
There are a few lines that must be change to work with your sample code. First change the AuthenticaitonContext to match your Azure AD domain/tenant name:
var ac = new AuthenticationContext("https://login.windows.net/irm.se");
Next look at the code part which acquires a token – this is when the login dialog pops up and asks the user to log in using his or hers organizational account. This line corresponds to the web API uri, which is the same as the “ida:Audience” in your web.config file, so update it to match that value:
var ar1 = ac.AcquireToken("https://irm.se/johandanforth",
The next line is the client id of the application client you created in Azure AD, look it up and change the id accordingly:
The last line is the redirect-uri of the client, look it up on the same page in the Azure management portal:
You must also modify the line with the call to the web API method to match your web server localhost settings:
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:44310/api/values");
Now, start the web API program in debug mode and wait until you see the Home Page, then right click and start debug of the WPF client. Click the button and you should be prompted to log in with your organizational account (this is the look of it in Swedish):
After a successful login, the code continues and you should be greeted with this:
Still with me?
Deploy to Azure
This is all well and good (hopefully), but we want to deploy our web API to Azure and run our clients against it in the cloud. To do that we need to:
1) Create a web site to host our web API in Azure
2) Publish our code to the site
3) Create an Azure AD resource for the web API (VS does this for you)
4) Modify the manifest for the web API (like before)
5) Give the client permission to the new resource (like before)
6) Update web.config and the client code to match the IDs and URIs of the new resources (ida:Audience == APP ID URI == the resource you want to access)
7) Publish the code again (to get the updated web.config uploaded)
Here’s some quick shots of some of the steps. First create a web site in Azure by selecting “WEB SITES” in the left hand menu of the Azure Portal, press the big plus-sign down in the corner and create a custom web site. I’m calling mine “johandanforth” (ignore the error message )
Now go back to Visual Studio, right click the web API project and select “Publish…”.
Press the “Import…” button to download and import the publishing profile of the web site you created, and select the newly created Web Site in the dropdown. Click OK.
You have to authenticate one or two times to get past these steps, but should finally get to the last step of the Publish process:
When Visual Studio is done publishing, a browser page will open up with the Home Page showing:
Visual Studio should now have created a new application resource in the Azure Active Directory, so get back to the portal and have a look at the list of AD applications. A resource named “WebApp-xxxxxxxxx.azurewebsites.net” should be listed there. Note – you may have to sign out and sign in to the portal to show the web api resource. This has happened to me a couple of times!
Click on the resource and look at the details in the CONFIGURE tab.
Copy the name of the “APP ID URI” and past it into the “ida:Audience” value in the web.config file of your web API project in Visual Studio:
<add key="ida:Audience" value="https://irm.se/WebApp-johandanforth.azurewebsites.net" />
The same value must also be updated in the WPF client:
var ar1 = ac.AcquireToken(https://irm.se/WebApp-johandanforth.azurewebsites.net,
You must also (of course) update the call to the web API method to point at the web site in the cloud:
var request = new HttpRequestMessage(HttpMethod.Get, "https://johandanforth.azurewebsites.net/api/values");
We’re not done yet though… now you have to do the same steps you did for the localhost resource earlier - download and update the manifest file for the web API resource and give the client resource permission to use the service.
Finally (yes finally) – publish the web API project again to get the updated web.config file to the cloud site!
Once the code is published, you should be able to run the client successfully.
Please give feedback if you have problems with any step/s of this walkthrough. Other questions, bugs and such is better asked on the Windows Azure Active Directory forum. I’m still learning these things and trying to keep up with the changes