DEV Community

Robertino
Robertino

Posted on • Originally published at auth0.com

Call a Protected API from a .NET MAUI App

Original post written by Andrea Chiarelli for Auth0 blog.

Learn how to call a protected API from your .NET MAUI application.


One of the most common activities a native application does after user authentication is calling an API. Also, if the application authenticates its users, the API it calls is most likely protected from unauthorized access. Let’s see how to make requests to a protected API with your .NET MAUI application.

Prerequisites

Before starting, make sure you have installed everything you need to run the sample project that goes with this article on your machine. In particular, you need the latest .NET 7.0 SDK and the additional components that depend on your development and target platforms. Please, refer to this document to learn more and set up your development environment.

You can use the .NET CLI to build and run your projects. If you decide to use Visual Studio, at the time of writing, you need Visual Studio 2022 17.4 Preview 2.1 or greater on Windows and Visual Studio for Mac 17.4 Preview on macOS.

Please, take into account the possibility that something could not work as expected or that changes may happen after this article is published.

The Sample Application

This article will show you how to call a protected API from a .NET MAUI application by guiding you in the process of modifying an existing app. You can download this application and the sample ASP.NET Core Web API by running the following command in a terminal window:

git clone --branch starting-point --single-branch https://github.com/auth0-blog/dotnet-maui-auth0-call-api.git
Enter fullscreen mode Exit fullscreen mode

This command will create a dotnet-maui-auth0-call-api folder and will download two .NET projects there. You will find these projects in two subfolders: dotnet-maui-auth0-app and api_aspnet-core_csharp_hello-world.

The dotnet-maui-auth0-app folder contains a basic .NET MAUI application that authenticates users using Auth0. To learn more about the details of building this application, check out this blog post, which explains how to add authentication to a .NET MAUI application.

The api_aspnet-core_csharp_hello-world folder contains a simple ASP.NET Core Web API with some endpoints protected using Auth0. This Web API project is a code sample from the Auth0 Developer Resources. Check out this page to learn more about this ASP.NET Core project.

Throughout this article, you will modify the .NET MAUI application to include a button to call a protected API implemented in the ASP.NET Core Web API project.

Register with Auth0

As the first step, let's register and configure both the .NET MAUI application and the Web API with Auth0. You need an Auth0 account. If you don't have it yet, you can sign up for a free one.

Configure the .NET MAUI application

Once in the Auth0 dashboard, move to the Applications section and follow these steps:

  1. Click on Create Application.
  2. Provide a friendly name for your application (for example, MAUI App) and choose Native as the application type.
  3. Finally, click the Create button.

These steps make Auth0 aware of your .NET MAUI application. After creating the application, move to the Settings tab and take note of your Auth0 domain and client ID. You will use them shortly.

Then, in the same form, scroll down to the Application URIs section and assign the value myapp://callback to both the Allowed Callback URLs and the Allowed Logout URLs fields.

The first value tells Auth0 which URL to call back after the user authenticates. The second value tells Auth0 which URL the user should be redirected to after their logout. Even if your .NET MAUI is not a web application, it can catch this URI.

Click the Save Changes button to apply them.

Now, go to the dotnet-maui-auth0-app folder and open the MauiProgram.cs file. In this file, look for the code highlighted in the following code snippet:

//dotnet-maui-auth0-app/MauiProgram.cs

using Microsoft.Extensions.Logging;
using MauiAuth0App.Auth0;

namespace MauiAuth0App;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
    // ...existing code...

    builder.Services.AddSingleton(new Auth0Client(new()
    {
      Domain = "<YOUR_AUTH0_DOMAIN>",
      ClientId = "<YOUR_CLIENT_ID>",
      Scope = "openid profile",
#if WINDOWS
            RedirectUri = "http://localhost/callback"
#else
      RedirectUri = "myapp://callback"
#endif
    }));

    return builder.Build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace the placeholders <YOUR_AUTH0_DOMAIN> and <YOUR_CLIENT_ID> with the respective values taken from the Auth0 dashboard.

Configure the ASP.NET Core Web API

Now, let's go back to the Auth0 dashboard. Navigate to the API section and click the Create API button. In the form that will be showing, provide a friendly name for your API (for example, Demo API) and a unique identifier in the URI format (for example, https://demo-api.com). Keep RS256 as the signing algorithm and click the Create button.

After the API registration on the Auth0 side, let's configure it on your machine. Go to the api_aspnet-core_csharp_hello-world/HelloworldApplication folder and open the appsettings.json file. Its content will look like the following:

//api_aspnet-core_csharp_hello-world/HelloworldApplication/appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Urls": "http://localhost:6060;https://localhost:6061",
  "Auth0": {
    "Domain": "{DOMAIN}",
    "Audience": "{API_IDENTIFIER}"
  }
}
Enter fullscreen mode Exit fullscreen mode

Replace the {DOMAIN} placeholder with your Auth0 domain, the same domain you got for the MAUI application, and the {API_IDENTIFIER} placeholder with the value you provided as a unique identifier of your API (https://demo-api.com, if you kept the value suggested above).

Run the applications

It's time to verify if everything works as expected.

In the api_aspnet-core_csharp_hello-world/HelloworldApplication folder, run the following command:

dotnet run
Enter fullscreen mode Exit fullscreen mode

After a few seconds, the ASP.NET Core application should be running and listening to the https://localhost:6061 address. You can check that everything works as expected by running the following command in a terminal window:

curl https://localhost:6061/api/messages/protected
Enter fullscreen mode Exit fullscreen mode

You should get the following response:

{"Message":"You are not authorized!"}
Enter fullscreen mode Exit fullscreen mode

You receive this message because the /api/messages/protected endpoint is protected and expects a valid access token in your HTTP request.

Now, go to the dotnet-maui-auth0-app folder and run your .NET MAUI application by using Visual Studio (currently mandatory for Windows) or one of the following commands, depending on the respective target platform:

# macOS target platform
dotnet build -t:Run -f net7.0-maccatalyst

# Android target platform
dotnet build -t:Run -f net7.0-android

# iOS target platform
dotnet build -t:Run -f net7.0-ios
Enter fullscreen mode Exit fullscreen mode

After a few seconds, you should get the following screen:

Running .NET MAUI application

Click the Log in button, sign in or sign up to the application and enter the home screen, which should appear like the following:

.NET MAUI app home screen with user profile

If everything works as expected, you are ready to make the .NET MAUI application call the api/messages/protected endpoint of the Web API.

Read more...

Top comments (0)