Saturday, August 24, 2019

Get IP Address Using C# Code

In general, we can find our IP address by CMD command in other words ipconfig . And, if you execute this on your Administrator Command Prompt then you will get the basic Network details like Host Name, IP Address and Gateway.
 
Network details

So, to handle this thing we have a few classes in the System.Net namespace. In this article, we deal with a few.

Procedure
Step 1: Start a new Console project in your Visual Studio.
Step 2: Add a namespace in your project as in the following:

Using System.Net;

Step 3: Before fetching the IP Address we need to know whose IP Address we really want. It's quite understood that we want our own PC. But, that must be specified in my code because computers are dumb.

So, we can fetch the machine Name (or Host Name) by the GetHostName() Method. And this is inside the Dns class.

Step 4: We are now ready to get the IP address of the Host.

For this we need to use the GetHostByName() method followed by AddressList array (first Index). 

And, in GetHostByName's argument we "host name".

Then, our code looks like:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net; //Include this namespace  
  6.    
  7.    
  8. namespace IpProto  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {   
  14.             string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
  15.             Console.WriteLine(hostName);  
  16.            // Get the IP  
  17.             string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();  
  18.             Console.WriteLine("My IP Address is :"+myIP);  
  19.             Console.ReadKey();  
  20.         }  
  21.     }  
  22. }    
The output will be:
Output

And, this is my Local IP so don't be confused. You will have your own.

How to: Sign in any Azure Active Directory user using the multi-tenant application pattern

If you offer a Software as a Service (SaaS) application to many organizations, you can configure your application to accept sign-ins from any Azure Active Directory (Azure AD) tenant. This configuration is called making your application multi-tenant. Users in any Azure AD tenant will be able to sign in to your application after consenting to use their account with your application.
If you have an existing application that has its own account system, or supports other kinds of sign-ins from other cloud providers, adding Azure AD sign-in from any tenant is simple. Just register your app, add sign-in code via OAuth2, OpenID Connect, or SAML, and put a "Sign in with Microsoft" button in your application.
 Note
This article assumes you’re already familiar with building a single tenant application for Azure AD. If you’re not, start with one of the quickstarts on the developer guide homepage.
There are four simple steps to convert your application into an Azure AD multi-tenant app:
  1. Update your application registration to be multi-tenant
  2. Update your code to send requests to the /common endpoint
  3. Update your code to handle multiple issuer values
  4. Understand user and admin consent and make appropriate code changes
Let’s look at each step in detail. You can also jump straight to this list of multi-tenant samples.

Update registration to be multi-tenant

By default, web app/API registrations in Azure AD are single tenant. You can make your registration multi-tenant by finding the Supported account types switch on the Authentication pane of your application registration in the Azure portal and setting it to Accounts in any organizational directory.
Before an application can be made multi-tenant, Azure AD requires the App ID URI of the application to be globally unique. The App ID URI is one of the ways an application is identified in protocol messages. For a single tenant application, it is sufficient for the App ID URI to be unique within that tenant. For a multi-tenant application, it must be globally unique so Azure AD can find the application across all tenants. Global uniqueness is enforced by requiring the App ID URI to have a host name that matches a verified domain of the Azure AD tenant.
By default, apps created via the Azure portal have a globally unique App ID URI set on app creation, but you can change this value. For example, if the name of your tenant was contoso.onmicrosoft.com then a valid App ID URI would be https://contoso.onmicrosoft.com/myapp. If your tenant had a verified domain of contoso.com, then a valid App ID URI would also be https://contoso.com/myapp. If the App ID URI doesn’t follow this pattern, setting an application as multi-tenant fails.
 Note
Native client registrations as well as Microsoft identity platform applications are multi-tenant by default. You don’t need to take any action to make these application registrations multi-tenant.

Update your code to send requests to /common

In a single tenant application, sign-in requests are sent to the tenant’s sign-in endpoint. For example, for contoso.onmicrosoft.com the endpoint would be: https://login.microsoftonline.com/contoso.onmicrosoft.com. Requests sent to a tenant’s endpoint can sign in users (or guests) in that tenant to applications in that tenant.
With a multi-tenant application, the application doesn’t know up front what tenant the user is from, so you can’t send requests to a tenant’s endpoint. Instead, requests are sent to an endpoint that multiplexes across all Azure AD tenants: https://login.microsoftonline.com/common
When Microsoft identity platform receives a request on the /common endpoint, it signs the user in and, as a consequence, discovers which tenant the user is from. The /common endpoint works with all of the authentication protocols supported by the Azure AD: OpenID Connect, OAuth 2.0, SAML 2.0, and WS-Federation.
The sign-in response to the application then contains a token representing the user. The issuer value in the token tells an application what tenant the user is from. When a response returns from the /common endpoint, the issuer value in the token corresponds to the user’s tenant.
 Important
The /common endpoint is not a tenant and is not an issuer, it’s just a multiplexer. When using /common, the logic in your application to validate tokens needs to be updated to take this into account.

Update your code to handle multiple issuer values

Web applications and web APIs receive and validate tokens from Microsoft identity platform.
 Note
While native client applications request and receive tokens from Microsoft identity platform, they do so to send them to APIs, where they are validated. Native applications do not validate tokens and must treat them as opaque.
Let’s look at how an application validates tokens it receives from Microsoft identity platform. A single tenant application normally takes an endpoint value like:
https://login.microsoftonline.com/contoso.onmicrosoft.com
and uses it to construct a metadata URL (in this case, OpenID Connect) like:
https://login.microsoftonline.com/contoso.onmicrosoft.com/.well-known/openid-configuration
to download two critical pieces of information that are used to validate tokens: the tenant’s signing keys and issuer value. Each Azure AD tenant has a unique issuer value of the form:
https://sts.windows.net/31537af4-6d77-4bb9-a681-d2394888ea26/
where the GUID value is the rename-safe version of the tenant ID of the tenant. If you select the preceding metadata link for contoso.onmicrosoft.com, you can see this issuer value in the document.
When a single tenant application validates a token, it checks the signature of the token against the signing keys from the metadata document. This test allows it to make sure the issuer value in the token matches the one that was found in the metadata document.
Because the /common endpoint doesn’t correspond to a tenant and isn’t an issuer, when you examine the issuer value in the metadata for /common it has a templated URL instead of an actual value:
https://sts.windows.net/{tenantid}/
Therefore, a multi-tenant application can’t validate tokens just by matching the issuer value in the metadata with the issuer value in the token. A multi-tenant application needs logic to decide which issuer values are valid and which are not based on the tenant ID portion of the issuer value.
For example, if a multi-tenant application only allows sign-in from specific tenants who have signed up for their service, then it must check either the issuer value or the tid claim value in the token to make sure that tenant is in their list of subscribers. If a multi-tenant application only deals with individuals and doesn’t make any access decisions based on tenants, then it can ignore the issuer value altogether.
In the multi-tenant samples, issuer validation is disabled to enable any Azure AD tenant to sign in.
For a user to sign in to an application in Azure AD, the application must be represented in the user’s tenant. This allows the organization to do things like apply unique policies when users from their tenant sign in to the application. For a single tenant application, this registration is simple; it’s the one that happens when you register the application in the Azure portal.
For a multi-tenant application, the initial registration for the application lives in the Azure AD tenant used by the developer. When a user from a different tenant signs in to the application for the first time, Azure AD asks them to consent to the permissions requested by the application. If they consent, then a representation of the application called a service principal is created in the user’s tenant, and sign-in can continue. A delegation is also created in the directory that records the user’s consent to the application. For details on the application's Application and ServicePrincipal objects, and how they relate to each other, see Application objects and service principal objects.
Illustrates consent to single-tier app
This consent experience is affected by the permissions requested by the application. Microsoft identity platform supports two kinds of permissions, app-only and delegated.
  • A delegated permission grants an application the ability to act as a signed in user for a subset of the things the user can do. For example, you can grant an application the delegated permission to read the signed in user’s calendar.
  • An app-only permission is granted directly to the identity of the application. For example, you can grant an application the app-only permission to read the list of users in a tenant, regardless of who is signed in to the application.
Some permissions can be consented to by a regular user, while others require a tenant administrator’s consent.
App-only permissions always require a tenant administrator’s consent. If your application requests an app-only permission and a user tries to sign in to the application, an error message is displayed saying the user isn’t able to consent.
Certain delegated permissions also require a tenant administrator’s consent. For example, the ability to write back to Azure AD as the signed in user requires a tenant administrator’s consent. Like app-only permissions, if an ordinary user tries to sign in to an application that requests a delegated permission that requires administrator consent, your application receives an error. Whether a permission requires admin consent is determined by the developer that published the resource, and can be found in the documentation for the resource. The permissions documentation for the Azure AD Graph API and Microsoft Graph API indicate which permissions require admin consent.
If your application uses permissions that require admin consent, you need to have a gesture such as a button or link where the admin can initiate the action. The request your application sends for this action is the usual OAuth2/OpenID Connect authorization request that also includes the prompt=admin_consent query string parameter. Once the admin has consented and the service principal is created in the customer’s tenant, subsequent sign-in requests do not need the prompt=admin_consent parameter. Since the administrator has decided the requested permissions are acceptable, no other users in the tenant are prompted for consent from that point forward.
A tenant administrator can disable the ability for regular users to consent to applications. If this capability is disabled, admin consent is always required for the application to be used in the tenant. If you want to test your application with end-user consent disabled, you can find the configuration switch in the Azure portal in the User settings section under Enterprise applications.
The prompt=admin_consent parameter can also be used by applications that request permissions that do not require admin consent. An example of when this would be used is if the application requires an experience where the tenant admin “signs up” one time, and no other users are prompted for consent from that point on.
If an application requires admin consent and an admin signs in without the prompt=admin_consentparameter being sent, when the admin successfully consents to the application it will apply only for their user account. Regular users will still not be able to sign in or consent to the application. This feature is useful if you want to give the tenant administrator the ability to explore your application before allowing other users access.
 Note
Some applications want an experience where regular users are able to consent initially, and later the application can involve the administrator and request permissions that require admin consent. There is no way to do this with a v1.0 application registration in Azure AD today; however, using the Microsoft identity platform (v2.0) endpoint allows applications to request permissions at runtime instead of at registration time, which enables this scenario. For more information, see Microsoft identity platform endpoint.
Your application may have multiple tiers, each represented by its own registration in Azure AD. For example, a native application that calls a web API, or a web application that calls a web API. In both of these cases, the client (native app or web app) requests permissions to call the resource (web API). For the client to be successfully consented into a customer’s tenant, all resources to which it requests permissions must already exist in the customer’s tenant. If this condition isn’t met, Azure AD returns an error that the resource must be added first.

Multiple tiers in a single tenant

This can be a problem if your logical application consists of two or more application registrations, for example a separate client and resource. How do you get the resource into the customer tenant first? Azure AD covers this case by enabling client and resource to be consented in a single step. The user sees the sum total of the permissions requested by both the client and resource on the consent page. To enable this behavior, the resource’s application registration must include the client’s App ID as a knownClientApplications in its application manifest. For example:
knownClientApplications": ["94da0930-763f-45c7-8d26-04d5938baab2"]
This is demonstrated in a multi-tier native client calling web API sample in the Related contentsection at the end of this article. The following diagram provides an overview of consent for a multi-tier app registered in a single tenant.
Illustrates consent to multi-tier known client app

Multiple tiers in multiple tenants

A similar case happens if the different tiers of an application are registered in different tenants. For example, consider the case of building a native client application that calls the Office 365 Exchange Online API. To develop the native application, and later for the native application to run in a customer’s tenant, the Exchange Online service principal must be present. In this case, the developer and customer must purchase Exchange Online for the service principal to be created in their tenants.
If it's an API built by an organization other than Microsoft, the developer of the API needs to provide a way for their customers to consent the application into their customers' tenants. The recommended design is for the third-party developer to build the API such that it can also function as a web client to implement sign-up. To do this:
  1. Follow the earlier sections to ensure the API implements the multi-tenant application registration/code requirements.
  2. In addition to exposing the API's scopes/roles, make sure the registration includes the "Sign in and read user profile" permission (provided by default).
  3. Implement a sign-in/sign-up page in the web client and follow the admin consent guidance.
  4. Once the user consents to the application, the service principal and consent delegation links are created in their tenant, and the native application can get tokens for the API.
The following diagram provides an overview of consent for a multi-tier app registered in different tenants.
Illustrates consent to multi-tier multi-party app
Users and administrators can revoke consent to your application at any time:
If an administrator consents to an application for all users in a tenant, users cannot revoke access individually. Only the administrator can revoke access, and only for the whole application.

Multi-tenant applications and caching access tokens

Multi-tenant applications can also get access tokens to call APIs that are protected by Azure AD. A common error when using the Active Directory Authentication Library (ADAL) with a multi-tenant application is to initially request a token for a user using /common, receive a response, then request a subsequent token for that same user also using /common. Because the response from Azure AD comes from a tenant, not /common, ADAL caches the token as being from the tenant. The subsequent call to /common to get an access token for the user misses the cache entry, and the user is prompted to sign in again. To avoid missing the cache, make sure subsequent calls for an already signed in user are made to the tenant’s endpoint.

Calling a Web API in a daemon app or long-running process

Overview

This sample demonstrates a Desktop daemon application calling a ASP.NET Web API that is secured using Azure Active Directory. This scenario is useful for situations where a headless, or unattended job, or process, needs to run as an application identity, instead of as a user's identity.
  1. The .Net TodoListDaemon application uses the Active Directory Authentication Library (ADAL) to obtain a JWT access token from Azure Active Directory (Azure AD). The token is requested using the OAuth 2.0 Client Credentials flow, where the client credential is a password. You could also use a certificate to prove the identity of the app. Client credential with certificate is the object of another sample: active-directory-dotnet-daemon-certificate-credential sample.
  2. The access token is used as a bearer token to authenticate the user when calling the TodoListService ASP.NET Web API.

Scenario

Once the service started, when you start the TodoListDaemon desktop application, it repeatedly:
  • adds items to the todo list maintained by the service
  • lists the existing items.
No user interaction is involved.

How to run this sample

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 that is an global admin of 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.

Step 1: Clone or download this repository

From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-daemon.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 application with your Azure Active Directory tenant

There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
If you want to use this automation, read the instructions in App Creation Scripts

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:
  1. Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
  2. If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant (using Switch Directory).
  3. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).

Register the service app (todoListService_web_daemon_v1)

  1. In App registrations page, select New registration.
  2. When the Register an application page appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example todoListService_web_daemon_v1.
    • In the Supported account types section, select Accounts in this organizational directory only ({tenant name}).
  3. Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
  5. In the list of pages for the app, select on Expose an API
    • For Application ID URI, set it to https://<your_tenant_name>/todoListService_web_daemon_v1 and pres Save

Step 2: Secure your Web API by defining Application Roles (permission)

If you don't do anything more, Azure AD will provide a token for any daemon application (using the client credential flow) requesting an access token for your Web API (for its App ID URI) In this step we are going to ensure that Azure AD only provides a token to the applications to which the Tenant admin grants consent. We are going to limit the access to our TodoList client by defining authorizations
Add an app role to the manifest
  1. While still in the blade for your application, click Manifest.
  2. Edit the manifest by locating the appRoles setting and adding an application roles. The role definition is provided in the JSON block below. Leave the allowedMemberTypes to "Application" only.
  3. Save the manifest.
The content of appRoles should be the following (the id can be any unique GUID)
"appRoles": [
    {
    "allowedMemberTypes": [ "Application" ],
    "description": "Accesses the todoListService_web_daemon_v1 as an application.",
    "displayName": "access_as_application",
    "id": "ccf784a6-fd0c-45f2-9c08-2f9d162a0628",
    "isEnabled": true,
    "lang": null,
    "origin": "Application",
    "value": "access_as_application"
    }
],
Ensure that tokens Azure AD issues tokens for your Web API only to allowed clients
The Web API tests for the app role (that's the developer way of doing it). But you can even ask Azure Active Directory to issue a token for your Web API only to applications which were approved by the tenant admin. For this:
  1. On the app Overview page for your app registration, select the hyperlink with the name of your application in Managed application in local directory (note this field title can be truncated for instance Managed application in ...)
When you select this link you will navigate to the Enterprise Application Overview page associated with the service principal for your application in the tenant where you created it. You can navigate back to the app registration page by using the back button of your browser.
  1. Select the Properties page in the Manage section of the Enterprise application pages
  2. If you want AAD to enforce access to your Web API from only certain clients, set User assignment required? to Yes.
Important security tip
By setting User assignment required? to Yes, AAD will check the app role assignments of the clients when they request an access token for the Web API (see app permissions below). If the client was not be assigned to any AppRoles, AAD would just return invalid_client: AADSTS501051: Application xxxx is not assigned to a role for the xxxx
If you keep User assignment required? to NoAzure AD won’t check the app role assignments when a client requests an access token to your Web API. Therefore, any daemon client (that is any client using client credentials flow) would be able to obtain the access token for the Web API just by specifying its audience (App ID URi). Now, there is a second level of security as your Web API can, as is done in this sample, verify that the application has the right role (which was authorized by the tenant admin). It does it by validating that the access token has a roles claim, and that this claims contains access_as_application.
  1. Select Save

Register the client app (todoList_web_daemon_v1)

  1. In App registrations page, select New registration.
  2. When the Register an application page appears, enter your application's registration information:
    • In the Name section, enter a meaningful application name that will be displayed to users of the app, for example todoList_web_daemon_v1.
    • In the Supported account types section, Accounts in this organizational directory only ({tenant name}).
  3. Select Register to create the application.
  4. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
  5. From the Certificates & secrets page, in the Client secrets section, choose New client secret:
    • Type a key description (of instance app secret),
    • Select a key duration of either In 1 yearIn 2 years, or Never Expires.
    • When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
    • You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
  6. In the list of pages for the app, select API permissions
    • Click the Add a permission button and then,
    • Ensure that the My APIs tab is selected
    • In the list of APIs, select the API todoListService_web_daemon_v1
      • In the Application Permissions section, ensure that the right permissions are checked: access_as_application'. Use the search box if necessary.
      • Select the Add permissions button
  7. You can remove the default permission User.Read as our client is a daemon app. there is no user.
  8. At this stage permissions are assigned correctly. However, by definition, daemon applications does not allow interaction. Therefore no consent can be presented via a UI and accepted to use the service app. The tenant admin need to consent for the client to access your application. for this Click the Grant/revoke admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all account in the tenant. You need to be an Azure AD tenant admin to do this.

Step 3: Configure the sample to use your Azure AD tenant

In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the solution in Visual Studio to configure the projects

Configure the service project

Note: if you used the setup scripts, the changes below will have been applied for you
  1. Open the TodoListService\Web.Config file
  2. Find the app key ida:Tenant and replace the existing value with your Azure AD tenant name.
  3. Find the app key ida:Audience and replace the existing value with the App ID URI you registered earlier for the todoListService_web_daemon_v1 app. For instance use https://<your_tenant_name>/todoListService_web_daemon_v1, where <your_tenant_name> is the name of your Azure AD tenant.

Configure the client project

Note: if you used the setup scripts, the changes below will have been applied for you
  1. Open the TodoListDaemon\App.Config file
  2. Find the app key ida:Tenant and replace the existing value with your Azure AD tenant name.
  3. Find the app key ida:ClientId and replace the existing value with the application ID (clientId) of the todoList_web_daemon_v1 application copied from the Azure portal.
  4. Find the app key ida:AppKey and replace the existing value with the key you saved during the creation of the todoList_web_daemon_v1 app, in the Azure portal.
  5. Find the app key todo:TodoListResourceId and replace the existing value with the App ID URI you registered earlier for the todoListService_web_daemon_v1 app. For instance use https://<your_tenant_name>/todoListService_web_daemon_v1, where <your_tenant_name> is the name of your Azure AD tenant.
  6. Find the app key todo:TodoListBaseAddress and replace the existing value with the base address of the todoListService_web_daemon_v1 project (by default https://localhost:44321/).
NOTE: The TodoListService's ida:Audience and TodoListDaemon's todo:TodoListResourceId app key values must not only match the App ID URI you configured, but they must also match each other exactly. This mach includes casing. Otherwise calls to the TodoListService /api/todolist endpoint will fail with "Error: unauthorized".

Step 4: Run the sample

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.
See the scenario section above to understand how to run the sample

How to deploy this sample to Azure

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.

Create and Publish the TodoListService to an Azure Web Site

  1. Sign in to the Azure portal.
  2. 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-contoso.azurewebsites.net. Click Create Web Site.
  3. 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.
  4. 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.
  5. Click on Settings and in the Connection tab, update the Destination URL so that it is https, for example https://TodoListService-contoso.azurewebsites.net. Click Next.
  6. On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Save. Click on Publish on the main screen.
  7. 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.

Update the Active Directory tenant application registration for TodoListService

  1. Navigate to the Azure portal.
  2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant containing the TodoListService application.
  3. On the applications tab, select the TodoListService application.
  4. From the Settings -> Reply URLs menu, update the Sign-On URL, and Reply URL fields to the address of your service, for example https://TodoListService-contoso.azurewebsites.net. Save the configuration.

Update the TodoListDaemon to call the TodoListService Running in Azure Web Sites

  1. In Visual Studio, go to the TodoListDaemon project.
  2. Open TodoListDaemon\App.Config. Only one change is needed - update the todo:TodoListBaseAddress key value to be the address of the website you published, for example, https://TodoListService-contoso.azurewebsites.net.
  3. 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.

About The Code

Client side: the daemon app

The code acquiring a token is located entirely in the TodoListDaemon\Program.cs file. The Authentication context is created (line 68)
authContext = new AuthenticationContext(authority);
Then a ClientCredential is instantiated (line 69), from the TodoListDaemon application's Client ID and the application secret (appKey).
clientCredential = new ClientCredential(clientId, appKey);
This instance of ClientCredential is used in the PostTodo() and GetTodo() methods as an argument to AcquireTokenAsync to get a token for the Web API (line 96 and 162)
result = await authContext.AcquireTokenAsync(todoListResourceId, clientCredential);
This token is then used as a bearer token to call the Web API (line 127 and 193)
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken)

Service side: how the protected API

On the service side, the code directing ASP.NET to validate the access token is in App_Start\Startup.Auth.cs. It only validates the audience of the application (the App ID URI)
 public partial class Startup
 {
  // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
  public void ConfigureAuth(IAppBuilder app)
  {
   app.UseWindowsAzureActiveDirectoryBearerAuthentication(
      new WindowsAzureActiveDirectoryBearerAuthenticationOptions
      {
       Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
       TokenValidationParameters = new TokenValidationParameters
       {
        ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
       }
      });
   }
}
However, the controllers also validate that the client has a roles claim of value access_as_application. It returns an Unauthorized error otherwise.
 public IEnumerable<TodoItem> Get()
 {
  //
  // The roles claim tells what permissions the client application has in the service.
  // In this case we look for a roles value of access_as_application
  //
  Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("roles");
  if (scopeClaim == null || (scopeClaim.Value != "access_as_application"))
  {
   throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized,
      ReasonPhrase = "The 'roles' claim does not contain 'access_as_application'or was not found" });
  }
  ...
 }

How to recreate this sample

First, in Visual Studio create an empty solution to host the projects. Then, follow the following steps to create each project.

Creating the TodoListService Project

  1. In the solution, create a new ASP.Net MVC web API project called TodoListService and while creating the project:
    • Click the Change Authentication button,
    • Select Organizational Accounts, Cloud - Single Organization,
    • Enter the name of your Azure AD tenant,
    • and set the Access Level to Single Sign On. You will be prompted to sign in to your Azure AD tenant.
    NOTE: You must sign in with a user that is in the tenant; you cannot, during this step, sign in with a Microsoft account.
  2. In the folder, add a new class called TodoItem.cs. Copy the implementation of TodoItem from this sample into the class.
  3. Add a new, empty, Web API 2 controller called TodoListController.
  4. Copy the implementation of the TodoListController from this sample into the controller. Don't forget to add the [Authorize] attribute to the class.
  5. In TodoListController resolving missing references by adding using statements for System.Collections.ConcurrentTodoListService.ModelsSystem.Security.Claims.

Creating the TodoListDaemon Project

  1. In the solution, create a new Windows --> Console Application called TodoListDaemon.
  2. Add the (stable) Active Directory Authentication Library (ADAL) NuGet, Microsoft.IdentityModel.Clients.ActiveDirectory, version 1.0.3 (or higher) to the project.
  3. Add assembly references to System.Net.HttpSystem.Web.Extensions, and System.Configuration.
  4. Add a new class to the project called TodoItem.cs. Copy the code from the sample project file of the same name into this class, completely replacing the code in the new file.
  5. Copy the code from Program.cs in the sample project into the file of the same name in the new project, completely replacing the code in the new file.
  6. In app.config create keys for ida:AADInstanceida:Tenantida:ClientIdida:AppKeytodo:TodoListResourceId, and todo:TodoListBaseAddress and set them accordingly. For the global Azure cloud, the value of ida:AADInstance is https://login.windows.net/{0}.
Finally, in the properties of the solution itself, set both projects as startup projects.

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...