Skip to content

An ASP.NET Core Web App which lets sign-in users (including in your org, many orgs, orgs + personal accounts, sovereign clouds) and call Web APIs (including Microsoft Graph)

License

Notifications You must be signed in to change notification settings

johnjv481/Web-app-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

How to deploy this sample to Azure

This tutorial has one WebApp and some chapters have a Web API project. To deploy them to Azure Web Sites, you'll need to perform these steps for each project:

  • create an Azure Web Site with a unique name
  • 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 WebApp-OpenIDConnect-DotNet-code-v2 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 --> Web App, and give your web site a name, for example, WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net.
  3. Thereafter select the Subscription, Resource Group, App service plan and Location. OS will be Windows and Publish will be Code.
  4. Click Create and wait for the App Service to be created.
  5. Once you get the Deployment succeeded notification, then click on Go to resource to navigate to the newly created App service.
  6. Do not activate App service authentication: your application handles everything by itself

If your project uses SQL Server, please follow these steps

  1. The following steps provide instructions to create a Sql database that the sample needs. If you already have a Sql Server and database present and a connection string available, skip the steps till we ask you to provide the connections string in the Application Settings.
  2. Click Create a resource in the top left-hand corner again, select Databases --> SQL Database, to create a new database. Follow the Quickstart tutorial if needed.
  3. You can name the Sql server and database whatever you want to.
  4. Select or create a database server, and enter server login credentials. Carefully note down the username and password for the Sql server as you'll need it when constructing your Sql connection string later.
  5. Wait for the Deployment succeeded notification, then click on Go to resource to navigate to the newly created database's manage screen.
  6. Click on Connection Strings on left menu and copy the ADO.NET (SQL authentication) connection string. Populate User ID={your_username};Password={your_password}; with values your provided during database creation.Copy this connection string.
  7. Click on Application settings in the left menu of the App service and add the copied Sql connection string in the Connection strings section as DefaultConnection.
  8. Choose SQLAzure in the Type dropdown. Save the setting.

Update the redirect URLs

  1. Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations.
  2. In the resultant screen, select the WebApp-OpenIDConnect-DotNet-code-v2 application.
  3. In the Authentication tab:
    • In the Redirect URIs section, select Web in the combo-box and add the following redirect URIs.
      • https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net
      • https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net/signin-oidc
    • In the Advanced settings section set Logout URL to https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net/signout-oidc
  4. In the Branding tab:
    • Update the Home page URL to the address of your app service, for example https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net.
    • Save the configuration.
  5. If your application calls a web api, make sure to apply the necessary changes on the project appsettings.json, so it calls the published API URL instead of localhost.

Publishing the sample

  1. From the Overview tab of the App Service, download the publish profile by clicking the Get publish profile link and save it. Other deployment mechanisms, such as from source control, can also be used.
  2. Switch to Visual Studio and go to the WebApp-OpenIDConnect-DotNet-code-v2 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.
  3. Click on Configure and in the Connection tab, update the Destination URL so that it is a https in the home page url, for example https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net. Click Next.
  4. On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Save. Click on Publish on the main screen.
  5. 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.

Case of web apps deployed to App Services as Linux containers

What is the issue?

Normally, Microsoft Identity Web computes the redirect URI automatically depending on the deployed URL.

However, when you deploy web apps to App Services as Linux containers, your application will be called by App Services on an HTTP address, whereas its registered redirect URI in the app registration will be HTTPS.

This means that when a user browses to the web app, they will be redirected to login.microsoftonline.com as expected, but with:

redirect_uri=http://<your app service name>.azurewebsites.net/signin-oidc

instead of

redirect_uri=https://<your app service name>.azurewebsites.net/signin-oidc

How to fix it?

In order to get the right result, the guidance from the ASP.NET Core team for working with proxies is in Configure ASP.NET Core to work with proxy servers and load balancers. You should address the issue centrally by using UseForwardedHeaders to fix the request fields, like scheme.

The container scenario should have been addressed by default in .NET Core 3.0. See Forwarded Headers Middleware Updates in .NET Core 3.0 preview 6. If there are issues with this for you, please contact the ASP .NET Core team https://github.com/dotnet/aspnetcore, as they will be the right team to assist with this.

Key Vault and Managed Service Identity (MSI)

Secure key management is essential to protect data in the cloud. Use Azure Key Vault to encrypt certicates/keys and small secrets like passwords that use keys stored in hardware security modules (HSMs). Then Microsoft.Identity.Web leverages Managed Service Identity to retrieve these certificates. For details see https://aka.ms/ms-id-web-certificates

If you want to retrieve passwords, instead of certificates, see the app-service-msi-keyvault-dotnet sample as a guide on how to use Azure Key Vault from App Service with Managed Service Identity (MSI).

MSAL token cache on distributed environments

The samples in this tutorial have their token cache providers configured for apps running on a single machine. On a production environment, these apps could be deployed in many machines for scalability purpose, so the token cache provider needs to be configured accordingly for this distributed architecture.

These are the necessary changes for each cache provider option:

In memory

If you want to use in memory cache, use this configuration on Startup.cs:

services.AddDistributedTokenCaches()
.AddDistributedMemoryCache();

Redis

If you want to use a distributed Redis cache, use this configuration on Startup.cs:

services.AddDistributedTokenCaches()
.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "<your_redis_primary_connection_string_here>";
    options.InstanceName = "<your_redis_instance_name>";
});

SQL Server

There are two options for distributed SQL cache:

If you want to use .Net Core distributed cache extensions

Create the cache database by running the CLI (change the parameters according to your configurations)

dotnet tool install --global dotnet-sql-cache
dotnet sql-cache create "<your DB connection string>" dbo <cacheTableName>
//For example: dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=My_Database;Integrated Security=True;" dbo TokenCache

Then use this configuration on Startup.cs:

services.AddDistributedTokenCaches()
.AddDistributedSqlServerCache(options =>
{
    options.ConnectionString = "<your_sql_connection_string_here>";
    options.SchemaName = "dbo";
    options.TableName = "<your_cache_table_name_here>";
});

If you want to configure DataProtection for distributed environments

You have to configure the key ring storage to a centralized location. It could be in Azure Key Vault or on a UNC share.

Note: If you change the key persistence location, the system no longer automatically encrypts keys at rest. It is recommended that you use one of the ProtectKeysWith* methods listed in this doc.

For Azure Key Vault, configure the system with PersistKeysToAzureBlobStorage (also consider using ProtectKeysWithAzureKeyVault) in the Startup class:

services.AddDataProtection()
.PersistKeysToAzureBlobStorage("<storage account connection or uri>");

Note: Your app must have Unwrap Key and Wrap Key permissions to the Azure Key Vault.

For UNC share, configure the system with PersistKeysToFileSystem (also consider using ProtectKeysWithCertificate) in the Startup class:

services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"));

If you (really) want to enable App services authentication

You don't need to enable app service authentication. If you do, depending on whether you enable or not App service authentication, the redirect URI will be different:

Scenario Redirect URI
Run on your developer box with IIS https://localhost:44321/signin-oidc
Run on your developer box with Kestrel profile https://localhost:5001/signin-oidc
Deployed to app service without app service authentication https://appServiceBaseUri/signin-oidc
Deployed to app service with app service authentication https://appServiceBaseUri/.auth/login/aad/callback

Therefore depending on the scenarios you want to run, you should add the corresponding redirect URI to the app registration

Community Help and Support

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 [azure-active-directory] [msal] [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.

Consider taking a moment to share your experience with us.

More information

For more information, see MSAL.NET's conceptual documentation:

About

An ASP.NET Core Web App which lets sign-in users (including in your org, many orgs, orgs + personal accounts, sovereign clouds) and call Web APIs (including Microsoft Graph)

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published