Add authentication to your Windows (UWP) app

In this tutorial, you add Microsoft authentication to the TodoApp project using Azure Active Directory. Before completing this tutorial, ensure you've created the project and deployed the backend.

Tip

Although we use Azure Active Directory for authentication, you can use any authentication library you wish with Azure Mobile Apps.

Add authentication to your backend service

Your backend service is a standard ASP.NET 6 service. Any tutorial that shows you how to enable authentication for an ASP.NET 6 service will work with Azure Mobile Apps.

To enable Azure Active Directory authentication for your backend service, you need to:

  • Register an application with Azure Active Directory.
  • Add authentication checking to the ASP.NET 6 backend project.

Register the application

First, register the web API in your Azure Active Directory tenant and add a scope by following these steps:

  1. Sign in to the Azure portal.

  2. If you have access to multiple tenants, use the Directories + subscriptions filter in the top menu to switch to the tenant in which you want to register the application.

  3. Search for and select Azure Active Directory.

  4. Under Manage, select App registrations > New registration.

    • Name: enter a name for your application; for example, TodoApp Quickstart. Users of your app will see this name. You can change it later.
    • Supported account types: Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox)
  5. Select Register.

  6. Under Manage, select Expose an API > Add a scope.

  7. For Application ID URI, accept the default by selecting Save and continue.

  8. Enter the following details:

    • Scope name: access_as_user
    • Who can consent?: Admins and users
    • Admin consent display name: Access TodoApp
    • Admin consent description: Allows the app to access TodoApp as the signed-in user.
    • User consent display name: Access TodoApp
    • User consent description: Allow the app to access TodoApp on your behalf.
    • State: Enabled
  9. Select Add scope to complete the scope addition.

  10. Note the value of the scope. It will be api://<client-id>/access_as_user. You'll need the scope when configuring the client. This will be referred to as the Web API Scope.

  11. Select Overview.

  12. Note the Application (client) ID in the Essentials section as you'll need this value to configure the backend service later on. This will be referred to as the Web API Application ID.

Open Visual Studio and select the TodoAppService.NET6 project.

  1. Right-click on the TodoAppService.NET6 project, then select Manage NuGet Packages....

  2. In the new tab, select Browse, then enter Microsoft.Identity.Web in the search box.

    Screenshot of adding the M S A L NuGet in Visual Studio.

  3. Select the Microsoft.Identity.Web package, then press Install.

  4. Follow the prompts to complete the installation of the package.

  5. Open Program.cs. Add the following to the list of using statements:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
  1. Add the following code directly above the call to builder.Services.AddDbContext():
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  .AddMicrosoftIdentityWebApi(builder.Configuration);
builder.Services.AddAuthorization();
  1. Add the following code directly above the call to app.MapControllers():
app.UseAuthentication();
app.UseAuthorization();

Your Program.cs should now look like this:

using Microsoft.AspNetCore.Datasync;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using TodoAppService.NET6.Db;
  
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
  
if (connectionString == null)
{
  throw new ApplicationException("DefaultConnection is not set");
}
  
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  .AddMicrosoftIdentityWebApi(builder.Configuration);
builder.Services.AddAuthorization();
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDatasyncControllers();
  
var app = builder.Build();
  
// Initialize the database
using (var scope = app.Services.CreateScope())
{
  var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
  await context.InitializeDatabaseAsync().ConfigureAwait(false);
}
  
// Configure and run the web service.
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
  1. Edit the Controllers\TodoItemController.cs. Add an [Authorize] attribute to the class. Your class should look like this:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Datasync;
using Microsoft.AspNetCore.Datasync.EFCore;
using Microsoft.AspNetCore.Mvc;
using TodoAppService.NET6.Db;

namespace TodoAppService.NET6.Controllers
{
  [Authorize]
  [Route("tables/todoitem")]
  public class TodoItemController : TableController<TodoItem>
  {
    public TodoItemController(AppDbContext context)
      : base(new EntityTableRepository<TodoItem>(context))
    {
    }
  }
}
  1. Edit the appsettings.json. Add the following block:
  "AzureAD": {
    "Instance": "https://login.microsoftonline.com",
    "ClientId": "<client-id>",
    "TenantId": "common"
  },

Replace the <client-id> with the Web API Application ID that you recorded earlier. Once complete, it should look like this:

{
  "AzureAD": {
    "Instance": "https://login.microsoftonline.com",
    "ClientId": "<client-id>",
    "TenantId": "common"
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TodoApp;Trusted_Connection=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Publish your service to Azure again:

  1. Right-click on the TodoAppService.NET6 project, then select Publish....
  2. Select the Publish button in the top-right corner of the tab.

Open a browser to https://yoursite.azurewebsites.net/tables/todoitem?ZUMO-API-VERSION=3.0.0. Note that the service now returns a 401 response, which indicates that authentication is required.

Screenshot of the browser showing an error.

Add authentication to the app

The Microsoft Datasync Framework has built-in support for any authentication provider that uses a Json Web Token (JWT) within a header of the HTTP transaction. This application will use the Microsoft Authentication Library (MSAL) to request such a token and authorize the signed in user to the backend service.

Configure a native client application

You can register native clients to allow authentication to Web APIs hosted in your app using a client library such as the Microsoft Identity Library (MSAL).

  1. In the Azure portal, select Active Directory > App registrations > New registration.

  2. In the Register an application page:

    • enter a Name for your app registration. You may want to use the name native-quickstart to distinguish this one from the one used by your backend service.
    • Select Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g. Skype, Xbox).
    • In Redirect URI:
      • Select Public client (mobile & desktop)
      • Enter the URL quickstart://auth
  3. Select Register.

  4. Select API permissions > Add a permission > My APIs.

  5. Select the app registration you created earlier for your backend service. If you don't see the app registration, make sure that you added the access_as_user scope.

    Screenshot of the scope registration in the Azure portal.

  6. Under Select permissions, select access_as_user, and then select Add permissions.

  7. Select Authentication > Mobile and desktop applications.

  8. Check the box next to https://login.microsoftonline.com/common/oauth2/nativeclient.

  9. Check the box next to msal{client-id}://auth (replacing {client-id} with your application ID).

  10. Select Add URI, then add http://localhost in the field for extra URIs.

  11. Select Save at the bottom of the page.

  12. Select Overview. Make a note of the Application (client) ID as you'll need it later. This will be referred to as the Native Client Application ID.

We have defined three redirect URLs:

  • http://localhost is used by WPF applications.
  • https://login.microsoftonline.com/common/oauth2/nativeclient is used by UWP applications.
  • msal{client-id}://auth is used by mobile (Android and iOS) applications.

Open the TodoApp.sln solution in Visual Studio and set the TodoApp.UWPproject as the startup project. Add the Microsoft Identity Library (MSAL) to the TodoApp.UWP project:

Add the Microsoft Identity Library (MSAL) to the platform project:

  1. Right-click on the project, then select Manage NuGet Packages....

  2. Select the Browse tab.

  3. Enter Microsoft.Identity.Client in the search box, then press Enter.

  4. Select the Microsoft.Identity.Client result, then click Install.

    Screenshot of selecting the M S A L NuGet in Visual Studio.

  5. Accept the license agreement to continue the installation.

Add the native client ID and backend scope to the configuration.

Open the TodoApp.Data project and edit the Constants.cs file. Add constants for ApplicationId and Scopes:

  public static class Constants
  {
      /// <summary>
      /// The base URI for the Datasync service.
      /// </summary>
      public static string ServiceUri = "https://demo-datasync-quickstart.azurewebsites.net";

      /// <summary>
      /// The application (client) ID for the native app within Azure Active Directory
      /// </summary>
      public static string ApplicationId = "<client-id>";

      /// <summary>
      /// The list of scopes to request
      /// </summary>
      public static string[] Scopes = new[]
      {
          "<scope>"
      };
  }

Replace the <client-id> with the Native Client Application ID you received when registering the client application in Azure Active Directory, and the <scope> with the Web API Scope you copied when you used Expose an API while registering the service application.

Open the App.xaml.cs file in the TodoApp.UWP project.

Add the following using statements to the top of the file:

using Microsoft.Datasync.Client;
using Microsoft.Identity.Client;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

Replace the constructor and the TodoService code with the following:

public App()
{
    InitializeComponent();
    Suspending += OnSuspending;

    IdentityClient = GetIdentityClient();
    TodoService = new RemoteTodoService(GetAuthenticationToken);
}

public static IPublicClientApplication IdentityClient { get; set; }

public ITodoService TodoService { get; }

public IPublicClientApplication GetIdentityClient()
{
    var identityClient = PublicClientApplicationBuilder.Create(Constants.ApplicationId)
        .WithAuthority(AzureCloudInstance.AzurePublic, "common")
        .WithUseCorporateNetwork(false)
        .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
        .Build();
    return identityClient;
}

public async Task<AuthenticationToken> GetAuthenticationToken()
{
    var accounts = await IdentityClient.GetAccountsAsync();
    AuthenticationResult result = null;
    bool tryInteractiveLogin = false;

    try
    {
        result = await IdentityClient
            .AcquireTokenSilent(Constants.Scopes, accounts.FirstOrDefault())
            .ExecuteAsync()
            .ConfigureAwait(false);
    }
    catch (MsalUiRequiredException)
    {
        tryInteractiveLogin = true;
    }
    catch (Exception ex)
    {
        Debug.WriteLine($"MSAL Silent Error: {ex.Message}");
    }

    if (tryInteractiveLogin)
    {
        try
        {
            result = await IdentityClient
                .AcquireTokenInteractive(Constants.Scopes)
                .ExecuteAsync()
                .ConfigureAwait(false);
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"MSAL Interactive Error: {ex.Message}");
        }
    }

    return new AuthenticationToken
    {
        DisplayName = result?.Account?.Username ?? "",
        ExpiresOn = result?.ExpiresOn ?? DateTimeOffset.MinValue,
        Token = result?.AccessToken ?? "",
        UserId = result?.Account?.Username ?? ""
    };
}

The GetAuthenticationToken() method works with the Microsoft Identity Library (MSAL) to get an access token suitable for authorizing the signed-in user to the backend service. This function is then passed to the RemoteTodoService for creating the client. If the authentication is successful, the AuthenticationToken is produced with data necessary to authorize each request. If not, then an expired bad token is produced instead.

Test the app

You should be able to press F5 to run the app. When the app runs, a browser will be opened to ask you for authentication. The first time the app runs, you'll be asked to consent to the access:

Screenshot of the Azure Active Directory consent request.

Press Yes to continue to your app. The app will then run as before.

Next steps

Next, configure your application to operate offline by implementing an offline store.

Further reading