services | platforms | author |
---|---|---|
active-directory |
dotnet |
dstrockis |
A WPF application that calls a Web API running on ASP.NET 5 protected by Azure AD OAuth Bearer Authentication.
This sample demonstrates a .Net WPF application calling a web API that is secured using Azure AD. The .Net application uses the Active Directory Authentication Library (ADAL) to obtain a JWT access token through the OAuth 2.0 protocol. The access token is sent to the ASP.NET 5 Web API, which authenticates the user using the OWIN OAuth Bearer Authentication middleware.
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
To run this sample you will need:
- Visual Studio 2015
- An Internet connection
- An Azure subscription (a free trial is sufficient)
Every Azure subscription has an associated Azure Active Directory tenant. If you don't already have an Azure subscription, you can get a free subscription by signing up at https://azure.microsoft.com. All of the Azure AD features used by this sample are available free of charge.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-native-aspnet5.git
If you already have a user account in your Azure Active Directory tenant, you can skip to the next step. This sample will not work with a Microsoft account, so if you signed in to the Azure portal with a Microsoft account and have never created a user account in your directory before, you need to do that now. If you create an account and want to use it to sign-in to the Azure portal, don't forget to add the user account as a co-administrator of your Azure subscription.
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant.
- Sign in to the Azure management portal.
- Click on Active Directory in the left hand nav.
- Click the directory tenant where you wish to register the sample application.
- Click the Applications tab.
- In the drawer, click Add.
- Click "Add an application my organization is developing".
- Enter a friendly name for the application, for example "TodoListService", select "Web Application and/or Web API", and click next.
- For the sign-on URL, enter the base URL for the sample, which is by default
https://localhost:44322
. - For the App ID URI, enter
https://<your_tenant_name>/TodoListService
, replacing<your_tenant_name>
with the name of your Azure AD tenant. Click OK to complete the registration.
- Sign in to the Azure management portal.
- Click on Active Directory in the left hand nav.
- Click the directory tenant where you wish to register the sample application.
- Click the Applications tab.
- In the drawer, click Add.
- Click "Add an application my organization is developing".
- Enter a friendly name for the application, for example "TodoListClient-DotNet", select "Native Client Application", and click next.
- For the Redirect URI, enter
http://TodoListClient
. Click finish. - Click the Configure tab of the application.
- Find the Client ID value and copy it aside, you will need this later when configuring your application.
- In "Permissions to Other Applications", click "Add Application." Select "Other" in the "Show" dropdown, and click the upper check mark. Locate & click on the TodoListService, and click the bottom check mark to add the application. Select "Access TodoListService" from the "Delegated Permissions" dropdown, and save the configuration.
- Open the solution in Visual Studio 2015.
- In the TodoListService project, open the
config.json
file. - Find the
Tenant
property and replace the value with your AAD tenant name, e.g. contoso.onmicrosoft.com. - Find the app key
Audience
and replace the value with the App ID URI you registered earlier, for examplehttps://<your_tenant_name>/TodoListService
.
- In the TodoListClient project, open
App.config
. - Find the app key
ida:Tenant
and replace the value with your AAD tenant name. - Find the app key
ida:ClientId
and replace the value with the Client ID for the TodoListClient from the Azure portal. - Find the app key
ida:RedirectUri
and replace the value with the Redirect URI for the TodoListClient from the Azure portal, for examplehttp://TodoListClient
. - Find the app key
todo:TodoListResourceId
and replace the value with the App ID URI of the TodoListService, for examplehttps://<your_tenant_name>/TodoListService
- If you changed the default value, find the app key
todo:TodoListBaseAddress
and replace the value with the base address of the TodoListService project.
Since the web API is SSL protected, the client of the API (the web app) will refuse the SSL connection to the web API unless it trusts the API's SSL certificate. Use the following steps in Windows Powershell to trust the IIS Express SSL certificate. You only need to do this once. If you fail to do this step, calls to the TodoListService will always throw an unhandled exception where the inner exception message is:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
To configure your computer to trust the IIS Express SSL certificate, begin by opening a Windows Powershell command window as Administrator.
Query your personal certificate store to find the thumbprint of the certificate for CN=localhost
:
PS C:\windows\system32> dir Cert:\LocalMachine\My
Directory: Microsoft.PowerShell.Security\Certificate::LocalMachine\My
Thumbprint Subject
---------- -------
C24798908DA71693C1053F42A462327543B38042 CN=localhost
Next, add the certificate to the Trusted Root store:
PS C:\windows\system32> $cert = (get-item cert:\LocalMachine\My\C24798908DA71693C1053F42A462327543B38042)
PS C:\windows\system32> $store = (get-item cert:\Localmachine\Root)
PS C:\windows\system32> $store.Open("ReadWrite")
PS C:\windows\system32> $store.Add($cert)
PS C:\windows\system32> $store.Close()
You can verify the certificate is in the Trusted Root store by running this command:
PS C:\windows\system32> dir Cert:\LocalMachine\Root
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with the service project starting first.
Explore the sample by signing in, adding items to the To Do list, removing the user account, and starting again. Notice that if you stop the application without removing the user account, the next time you run the application you won't be prompted to sign-in again - that is the sample implements a persistent cache for ADAL, and remembers the tokens from the previous run.
NOTE: Remember, the To Do list is stored in memory in this TodoListService sample. Each time you run the TodoListService API, your To Do list will get emptied.
Coming soon.
##About The Code
Coming soon.
First, in Visual Studio 2015 CTP6 create an empty solution to host the projects. Then, follow these steps to create each project.
- In the solution, create a new "ASM.NET 5 MVC Web API" project called TodoListService.
- Enable SSL on the project by following the steps outlined in the below section.
- Add the
Microsoft.AspNet.Security.OAuthBearer
andMicrosoft.Framework.ConfigurationModel.Json
NuGets to the project. - Create a new
Models
folder, and add a new class to it calledTodoItem.cs
. Copy the implementation of TodoItem from this sample into the class. - Delete the existing
ValuesController.cs
, and add a new Web API controller class calledTodoListController
. - Copy the implementation of the TodoListController from this sample into the controller. Don't forget to add the
[Authorize]
attribute to the class. - In
TodoListController
resolving missing references by addingusing
statements forSystem.Collections.Concurrent
,TodoListService.Models
,System.Security.Claims
. - Add a new ASP.NET Configuration File called
config.json
to the project. Replace its contents with those of the sample. - Replace the implementation of
Startup.cs
with that of the sample, resolving any missing references such asMicrosoft.Framework.ConfigurationModel
.
- In the solution, create a new Windows --> WPF Application called TodoListClient.
- Add the (stable release) Active Directory Authentication Library (ADAL) NuGet,
Microsoft.IdentityModel.Clients.ActiveDirectory
to the project. - Add assembly references to
System.Net.Http
,System.Web.Extensions
,System.Security
, andSystem.Configuration
. - Add a new class to the project called
TodoItem.cs
. Copy the code from the sample project file of same name into this class, completely replacing the code in the file in the new project. - Add a new class to the project called
FileCache.cs
. Copy the code from the sample project file of same name into this class, completely replacing the code in the file in the new project. - Copy the markup from `MainWindow.xaml' in the sample project into the file of same name in the new project, completely replacing the markup in the file in the new project.
- Copy the code from
MainWindow.xaml.cs
in the sample project into the file of same name in the new project, completely replacing the code in the file in the new project. - In
app.config
create keys forida:AADInstance
,ida:Tenant
,ida:ClientId
,ida:RedirectUri
,todo:TodoListResourceId
, andtodo:TodoListBaseAddress
and set them accordingly. For the public Azure cloud, the value ofida:AADInstance
ishttps://login.windows.net/{0}
.
Finally, in the properties of the solution itself, set both projects as startup projects. Follow the steps in "How to Run This Sample" to configure and run each project.
These steps are temporarily necessary to enable SSL only for Visual Studio 2015: First, hit F5 to run the application. Once you see the homepage, you may close the browser and stop IIS Express. In a text editor, open the file %userprofile%\documents\IISExpress\config\applicatoinhost.confg
. Find the entry for your app in the <sites>
node. Add an https protocol binding to this entry for a port between 44300 and 44399, similar to the following:
<site name="WebApplication1" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="c:\users\billhie\documents\visual studio 2015\Projects\WebApplication1\WebApplication1" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:53756:localhost" />
<binding protocol="https" bindingInformation="*:44300:localhost" />
</bindings>
</site>
Save and close the file. In Visual Studio, open the properties page of your web app. In the Debug menu, enable the Launch Browser checkbox and enter the same URL as the protocol binding you added, e.g. https://localhost:44300/
. Your app will now run at this address.