ASP.NET Core
Your API verifies the session token your frontend sends and manages users with the secret key. The frontend is any
Zautha app, such as the React (Vite) quickstart’s on http://localhost:5173; it sends the
token as Authorization: Bearer <token>.
Before you start
Section titled “Before you start”- .NET 10 and a minimal API project (
dotnet new web). - An application in the dashboard: its publishable key and a secret key (shown once when you create it) are on the instance’s API keys page.
Install
Section titled “Install”dotnet add package Zautha.AspNetCoreAdd your keys
Section titled “Add your keys”User secrets keep the keys out of the project’s files while you develop:
dotnet user-secrets initdotnet user-secrets set "Zautha:PublishableKey" "pk_test_..."dotnet user-secrets set "Zautha:SecretKey" "sk_test_..."User secrets are read only in the Development environment. On your server, set the keys as the environment variables
Zautha__PublishableKey and Zautha__SecretKey.
Add the code
Section titled “Add the code”AddZauthaAuthentication accepts a token only when it was issued for one of appOrigins, which CORS allows too;
/api/me requires a signed-in user, reads them with the secret key and returns only what the browser may see.
using System.Security.Claims;using Zautha.AspNetCore;
// The frontends that call this API: allowed by CORS, and the only accepted origins of their session tokens.string[] appOrigins = ["http://localhost:5173"];
var builder = WebApplication.CreateBuilder(args);builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy.WithOrigins(appOrigins).WithHeaders("Authorization")));builder.Services.AddZauthaAuthentication(options =>{ options.PublishableKey = builder.Configuration["Zautha:PublishableKey"]; options.AuthorizedParties = appOrigins;});// The secret key (create one under API keys) stays on your server.builder.Services.AddZauthaClient(options => options.SecretKey = builder.Configuration["Zautha:SecretKey"]);builder.Services.AddAuthorization();
var app = builder.Build();app.UseCors();app.UseAuthentication();app.UseAuthorization();app.MapGet("/api/me", async (ClaimsPrincipal user, IZauthaClient zautha, CancellationToken ct) =>{ var me = await zautha.Users.GetAsync(user.GetZauthaAuth().UserId, ct); // Only what the browser may see: private metadata stays on the server. return Results.Ok(new { id = me.Id, primary_email_address = me.PrimaryEmailAddress, first_name = me.FirstName, last_name = me.LastName });}).RequireAuthorization();app.Run();Run it
Section titled “Run it”dotnet runSign in on your frontend and call /api/me with the session token: it answers with your user; without one it answers
401.
Next steps
Section titled “Next steps”Zautha.AspNetCore: reverification, roles and permissions, the Backend API client, webhooks.- Sessions and tokens: what is in the session token.
Zautha’s end-to-end tests run this setup in an ASP.NET Core example API.