services | platforms | author | level | client | service | endpoint |
---|---|---|---|---|---|---|
active-directory |
dotnet |
jmprieur |
300 |
.NET Desktop (Console) |
ASP.NET MVC Web API |
AAD V1 |
Authenticating to Azure AD non-interactively using a username & password or Windows Integrated Authentication
This sample demonstrates a .Net console application calling a web API that is secured using Azure AD. the application does not require user interaction through a Web browser:
- 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 web API to authenticate the user.
This sample shows you how to use ADAL to authenticate users via raw credentials (username and password, or Windows-integrated authentication) via a text-only interface. Information is available in the ADAL.NET conceptual documentation in Acquiring tokens with username and password and AcquireTokenSilentAsync using Integrated authentication on Windows (Kerberos)
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Looking for previous versions of this code sample? Check out the tags on the releases GitHub page.
[!Note] If you want to run this sample on Azure Government, navigate to the "Azure Government Deviations" section at the bottom of this page.
To run this sample, you'll need:
- Visual Studio 2017
- An Internet connection
- An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant
- A user account in your Azure AD tenant. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, 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.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-native-headless.git
Given that the name of the sample is pretty long, and so are the name of the referenced NuGet pacakges, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.
Step 2: Register the sample with your Azure Active Directory tenant and configure the code accordingly
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- either follow the steps in the paragraphs below (Step 2 and Step 3)
- or use PowerShell scripts that:
- automatically create for you the Azure AD applications and related objects (passwords, permissions, dependencies)
- modify the Visual Studio projects' configuration files.
If you want to use this automation, read the instructions in App Creation Scripts
As a first step you'll need to:
- Sign in to the Azure portal.
- On the top bar, click on your account, and then on Switch Directory.
- Once the Directory + subscription pane opens, choose the Active Directory tenant where you wish to register your application, from the Favorites or All Directories list.
- Click on All services in the left-hand nav, and choose Azure Active Directory.
In the next steps, you might need the tenant name (or directory name) or the tenant ID (or directory ID). These are presented in the Properties of the Azure Active Directory window respectively as Name and Directory ID
- In the Azure Active Directory pane, click on App registrations and choose New application registration.
- Enter a friendly name for the application, for example 'TodoListService-Headless' and select 'Web app / API' as the Application Type.
- For the sign-on URL, enter the base URL for the sample. By default, this sample uses
https://localhost:44321
. - Click Create to create the application.
- In the succeeding page, Find the Application ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
- Then click on Settings, and choose Properties.
- For the App ID URI, replace the guid in the generated URI 'https://<your_tenant_name>/<guid>', with the name of your service, for example, 'https://<your_tenant_name>/TodoListService-Headless' (replacing
<your_tenant_name>
with the name of your Azure AD tenant)
- In the Azure Active Directory pane, click on App registrations and choose New application registration.
- Enter a friendly name for the application, for example 'TodoListClient-Headless' and select 'Native' as the Application Type.
- For the Redirect URI, enter
https://<your_tenant_name>/TodoListClient-Headless
, replacing<your_tenant_name>
with the name of your Azure AD tenant. - Click Create to create the application.
- In the succeeding page, Find the Application ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
- Then click on Settings, and choose Properties.
- Configure Permissions for your application. To that extent, in the Settings menu, choose the 'Required permissions' section and then,
click on Add, then Select an API, and type
TodoListService-Headless
in the textbox. Then, click on Select Permissions and select Access 'TodoListService-Headless'.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the solution in Visual Studio to configure the projects
- Open the
TodoListService\Web.Config
file - Find the app key
ida:Tenant
and replace the existing value with your Azure AD tenant name. - Find the app key
ida:Audience
and replace the existing value with the App ID URI you registered earlier for the TodoListService-Headless app. For instance usehttps://<your_tenant_name>/TodoListService-Headless
, where<your_tenant_name>
is the name of your Azure AD tenant.
- Open the
TodoListClient\App.Config
file - Find the app key
ida:Tenant
and replace the existing value with your Azure AD tenant name. - Find the app key
ida:ClientId
and replace the existing value with the application ID (clientId) of theTodoListClient-Headless
application copied from the Azure portal. - Find the app key
todo:TodoListResourceId
and replace the existing value with the App ID URI you registered earlier for the TodoListService-Headless app. For instance usehttps://<your_tenant_name>/TodoListService-Headless
, where<your_tenant_name>
is the name of your Azure AD tenant. - Find the app key
todo:TodoListBaseAddress
and replace the existing value with the base address of the TodoListService-Headless project (by defaulthttps://localhost:44321
).
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.
Type the command add
. You will be prompted for your username and password. Enter them, then enter the description a new todo. That done, type the command list
. You will see that the command executes without prompting you again. You can clear the token cache by typing clear
, and leave the client by typing exit
.
Notice that if you stop the application without clearing the cache, 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.
This project has one WebApp / Web API projects. To deploy them to Azure Web Sites, you'll need, for each one, to:
- create an Azure Web Site
- publish the Web App / Web APIs to the web site, and
- update its client(s) to call the web site instead of IIS Express.
- Sign in to the Azure portal.
- Click Create a resource in the top left-hand corner, select Web + Mobile --> Web App, select the hosting plan and region, and give your web site a name, for example,
TodoListService-Headless-contoso.azurewebsites.net
. Click Create Web Site. - Once the web site is created, click on it to manage it. For this set of steps, download the publish profile by clicking Get publish profile and save it. Other deployment mechanisms, such as from source control, can also be used.
- Switch to Visual Studio and go to the TodoListService project. Right click on the project in the Solution Explorer and select Publish. Click Import Profile on the bottom bar, and import the publish profile that you downloaded earlier.
- Click on Settings and in the
Connection tab
, update the Destination URL so that it is https, for example https://TodoListService-Headless-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authentication
is NOT selected. Click Save. Click on Publish on the main screen. - Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.
- Navigate to the Azure portal.
- On the top bar, click on your account and under the Directory list, choose the Active Directory tenant containing the
TodoListService-Headless
application. - On the applications tab, select the
TodoListService-Headless
application. - From the Settings -> Properties and Settings -> Reply URLs menus, update the Sign-On URL, and Reply URL fields to the address of your service, for example https://TodoListService-Headless-contoso.azurewebsites.net. Save the configuration.
- In Visual Studio, go to the
TodoListClient-Headless
project. - Open
TodoListClient\App.Config
. Only one change is needed - update thetodo:TodoListBaseAddress
key value to be the address of the website you published, for example, https://TodoListService-Headless-contoso.azurewebsites.net. - Run the client! If you are trying multiple different client types (for example, .Net, Windows Store, Android, iOS) you can have them all call this one published web API.
NOTE: Remember, the To Do list is stored in memory in this TodoListService sample. Azure Web Sites will spin down your web site if it is inactive, and your To Do list will get emptied. Also, if you increase the instance count of the web site, requests will be distributed among the instances. To Do will, therefore, not be the same on each instance.
This sample shows how to use the OpenID Connect ASP.Net OWIN middleware to secure calls to an Asp.net Web API to users of a single Azure Active Directory tenant. The middleware is initialized in the Startup.Auth.cs
file, by passing it the URL of the Azure AD tenant (token issuer) and the AppId URI, which is the identifier by which the Web API is known to Windows Azure AD.
The middleware then takes care of:
- Downloading the Azure AD metadata, finding the signing keys, and finding the issuer name for the tenant.
- Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting them on ClaimsPrincipal.Current.
- Any tokens carrying a different Audience are meant for another resource and will be rejected.
To add an element to the todo list, first the program will try to acquire a token silently from the cache Program.cs, line 218, if this acquisition fails, the program asks for a user name password and creates an instance of UserCredential
. This is done in TextualPrompt(). Then it calls the AcquireTokenAsync
override with the UserCredential
in Program.cs, line 164.
Since this sample works on .NET framework, it also features the custom serialization of the token cache, which happens in FileCache.cs
If your PC is domain joined or AAD joined, you can also use the Windows-integrated security. For this, instead of calling TextualPrompt(), you need to uncomment the line creating an instance of UserCredential without parameters: See Program.cs
UserCredential uc = new UserCredential();
You can trigger the middleware to send an OpenID Connect sign-in request by decorating a class or method with the [Authorize]
attribute
If you get the following error: Inner Exception : AADSTS65001: The user or administrator has not consented to use the application with ID *your app ID* named 'TodoListClient'. Send an interactive authorization request for this user and resource
, then check that you have done bullet point 9 of Register the TodoListClient app
- In Visual Studio 2017, create a new
Visual C#
ASP.NET Web Application (.NET Framework)
. ChooseWeb Api
in the next screen. Leave the project's chosen authentication mode as the default, that is,No Authentication
. - Set SSL Enabled to be True. Note the SSL URL.
- Add the following ASP.Net OWIN middleware NuGets:
Microsoft.Owin.Security.ActiveDirectory
andMicrosoft.Owin.Host.SystemWeb
. - Add a class named
TodoItem
in theModels
folder. Add the propertiesTitle
andOwner
in this class. - Add a new
Web Api 2 Controller - Empty
namedTodoListController
in the service. - The
TodoListController
will have an in-memory list of ToDo items and methods to read and write from that list. Refer to the providedTodoListController
code for more details. - In the
App_Start
folder, create a classStartup.Auth.cs
.You will need to remove.App_Start
from the namespace name. Replace the code for theStartup
class with the code from the same file of the sample app. Be sure to take the whole class definition! The definition changes frompublic class Startup
topublic partial class Startup
- In
Startup.Auth.cs
resolve missing references by addingusing
statements as suggested by Visual Studio intellisense. - Right-click on the project, select Add, select "Class", and in the search box enter "OWIN". "OWIN Startup class" will appear as a selection; select it, and name the class
Startup.cs
. - In
Startup.cs
, replace the code for theStartup
class with the code from the same file of the sample app. Again, note the definition changes frompublic class Startup
topublic partial class Startup
. - If you want the user to be required to sign in before they can see any page of the api, then in the
HomeController
, decorate theHomeController
class with the[Authorize]
attribute. If you leave this out, the user will be able to see the home page of the app without having to sign in first, and can click the sign-in link on that page to get signed in. - In the
web.config
file, in<appSettings>
, create keys forida:Tenant
, andida:Audience
and set the values accordingly. - Almost done! Follow the steps in "Running This Sample" to register the application in your AAD tenant.
- In Visual Studio 2017, create a new
Visual C#
Console App (>NET Framework)
. - Add the NuGet packages:
Microsoft.Owin.Security.ActiveDirectory
,Newtonsoft.Json
andSystem.Net.Http
. - Add a reference for the
System.Security
assembly in the project. - In
Program.cs
, replace the code for theProgram
class with the code from the same file of the sample app. Resolve missing references by addingusing
statements as suggested by Visual Studio intellisense. - Add a new class called
FileCache.cs
in the project. It is a simple persistent cache implementation for a desktop application. It uses DPAPI for storing tokens in a local file. Replace the code for theFileCache
class with the code from the same file of the sample app. Be sure to take the whole class definition! - In the
FileCache.cs
class, resolve missing references by addingusing
statements as suggested by Visual Studio intellisense. - In
app.config
, in<appSettings>
, create keys forida:Tenant
,ida:ClientId
,ida:AADInstance
,todo:TodoListResourceId
andtodo:TodoListBaseAddress
and set the values accordingly. For the global Azure AD, the value ofida:AADInstance
ishttps://login.microsoftonline.com/{0}
.
In order to run this sample on Azure Government you can follow through the steps above with a few variations:
- Step 2:
- You must register this sample for your AAD Tenant in Azure Government by following Step 2 above in the Azure Government portal.
- Step 3:
- Before configuring the sample, you must make sure your Visual Studio is connected to Azure Government.
- Navigate to the Web.config file. Replace the
ida:AADInstance
property in the Azure AD section withhttps://login.microsoftonline.us/
.
Once those changes have been accounted for, you should be able to run this sample on Azure Government.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [adal
dotnet
].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
For more information, see ADAL.NET's conceptual documentation:
- Recommanded pattern to acquire a token
- Acquiring tokens with username and password
- AcquireTokenSilentAsync using Integrated authentication on Windows (Kerberos)
- Customizing Token cache serialization
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.