Sign in

.NET API Authentication Quickstart

Protect a .NET API using MonoCloud access token validation.

In this quickstart, you will:

  • Create an API resource on MonoCloud
  • Install the MonoCloud API Authentication .NET SDK
  • Protect ASP.NET Core endpoints with Bearer token validation
  • Read claims from the authenticated token

Prerequisites

Before you begin, make sure you have:

  • A MonoCloud account and tenant
  • The .NET SDK (6.0 or later)
  • An existing ASP.NET Core (minimal API) project
A complete working example is available at: https://github.com/monocloud/dotnet-api-authentication-quickstart

Configure MonoCloud

  1. In the MonoCloud Dashboard, create a new API
  2. Set the Audience (for example https://api.example.com) — this uniquely identifies your API
  3. Add a scope named example-api and mark the scope as a default scope
Keep this tab open. You'll need the Tenant Domain and Audience next.

Install the SDK

Install the SDK:

Terminal
dotnet add package MonoCloud.Authentication.Api

Configure the application

Add a MonoCloud section to your appsettings.json:

appsettings.json
{
  "MonoCloud": {
    "TenantDomain": "https://<your-domain>",
    "Audience": "https://<your-api-audience>"
  }
}

Protect your API

Update Program.cs:

Program.cs
using System.Security.Claims;
using MonoCloud.Authentication.Api;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(MonoCloudAuthenticationDefaults.AuthenticationScheme)
    .AddMonoCloudAuthentication(options =>
    {
        options.TenantDomain = builder.Configuration["MonoCloud:TenantDomain"];
        options.Audience = builder.Configuration["MonoCloud:Audience"];
    });

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

app.MapGet("/api/protected", (ClaimsPrincipal user) => new
{
    message = "Protected endpoint",
    claims = user.Claims.Select(claim => new { claim.Type, claim.Value }),
})
.RequireAuthorization();

app.Run();

How it works

The MonoCloud authentication handler:

  • Registers as a standard ASP.NET Core authentication scheme
  • Validates the incoming Bearer token
  • Verifies issuer, audience, and signature
  • Returns 401 Unauthorized if invalid
  • Populates HttpContext.User with the validated claims

.RequireAuthorization() ensures only requests with a valid access token reach the endpoint.

Run the application

Start the server:

Terminal
dotnet run -- --urls "http://localhost:3000"

Your API will be available at: http://localhost:3000

Everything after -- is passed to the application — --urls overrides the port assigned in Properties/launchSettings.json.

Test the protected route

The /api/protected route requires a valid access token.

Terminal
curl -H "Authorization: Bearer <your-access-token>" http://localhost:3000/api/protected
© 2024 MonoCloud. All rights reserved.