Protect a .NET API using MonoCloud access token validation.
In this quickstart, you will:
Before you begin, make sure you have:
A complete working example is available at: https://github.com/monocloud/dotnet-api-authentication-quickstart
https://api.example.com) — this uniquely identifies your APIexample-api and mark the scope as a default scopeKeep this tab open. You'll need the Tenant Domain and Audience next.
Install the SDK:
dotnet add package MonoCloud.Authentication.Api
Add a MonoCloud section to your appsettings.json:
{
"MonoCloud": {
"TenantDomain": "https://<your-domain>",
"Audience": "https://<your-api-audience>"
}
}
Update 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();
The MonoCloud authentication handler:
HttpContext.User with the validated claims.RequireAuthorization() ensures only requests with a valid access token reach the endpoint.
Start the server:
dotnet run -- --urls "http://localhost:3000"
Your API will be available at: http://localhost:3000
Everything after--is passed to the application —--urlsoverrides the port assigned inProperties/launchSettings.json.
The /api/protected route requires a valid access token.
curl -H "Authorization: Bearer <your-access-token>" http://localhost:3000/api/protected