Call a Protected API from a .NET MAUI App
Tags: dotnet, programming, tutorial
Published: 2022-11-09 15:00:32

> Original post written by [Andrea Chiarelli](https://auth0.com/blog/authors/andrea-chiarelli/) for Auth0 blog.

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

### <br>

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](https://dotnet.microsoft.com/en-us/download/dotnet/7.0) and the additional components that depend on your development and target platforms. Please, refer to [this document](https://docs.microsoft.com/en-us/dotnet/maui/get-started/first-app) to learn more and set up your development environment.

You can use the [.NET CLI](https://learn.microsoft.com/en-us/dotnet/core/tools/) 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:

```bash
git clone --branch starting-point --single-branch https://github.com/auth0-blog/dotnet-maui-auth0-call-api.git
```

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](https://auth0.com/blog/add-authentication-to-dotnet-maui-apps-with-auth0).

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](https://developer.auth0.com/resources). Check out [this page to learn more about this ASP.NET Core project](https://developer.auth0.com/resources/code-samples/api/aspnet-core-csharp/basic-authorization).

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 <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">sign up for a free one</a>.

### Configure the .NET MAUI application

Once in the Auth0 dashboard, move to the [Applications section](https://manage.auth0.com/#/applications) 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:

```csharp
//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();
	}
}
```

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](https://manage.auth0.com/#/apis) 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:

```json
//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}"
  }
}
```

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:

```bash
dotnet run
```

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:

```bash
curl https://localhost:6061/api/messages/protected
```

You should get the following response:

```bash
{"Message":"You are not authorized!"}
```

You receive this message because the `/api/messages/protected` endpoint is protected and expects a valid [access token](https://auth0.com/docs/secure/tokens/access-tokens) 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:

```bash
# 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
```

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

![Running .NET MAUI application](https://images.ctfassets.net/23aumh6u8s0i/63KS4f93QFWx884Kit2Xhf/5f829d8eced768787c431f8f7bb423c8/dotnet-maui-app-with-login-button.png)

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](https://images.ctfassets.net/23aumh6u8s0i/5PR5uqejvu4MdEac8yTN95/d1dcc0e70b37c66fd3a02de07c0ca3ae/dotnet-maui-app-home-screen-with-user-profile.png)

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...](https://auth0.com/blog/call-protected-api-from-dotnet-maui-application/?utm_source=devto&utm_medium=sc&utm_campaign=devto)