# .NET and ASP.NET Core

> Sign users in and protect APIs from ASP.NET Core or any .NET app with the 9in packages or AddOpenIdConnect.

Source: https://9in.io/docs/dotnet/

.NET apps sign users in as a **confidential client** (see [Server-rendered apps](https://9in.io/docs/server-apps/) for how that works). Use the 9in packages, [`9in.AspNetCore`](https://github.com/9in-io/dotnet) for ASP.NET Core and `9in` for any .NET app, or ASP.NET Core's own `AddOpenIdConnect` pointed at your issuer. Both packages target .NET 8 and .NET 10.

Create the application first: **Applications → Create application → Regular Web App**, with your callback URL (`https://your-app.com/nine/callback`) and logout URL (`https://your-app.com/`), and copy the client ID and secret.

## ASP.NET Core

```bash
dotnet add package 9in.AspNetCore
```

```json
{
  "Nine": {
    "Issuer": "https://acme.9in.io",
    "ClientId": "app_…",
    "Audience": "https://api.acme.com"
  }
}
```

```bash
dotnet user-secrets set "Nine:ClientSecret" "…"   # or NINE_CLIENT_SECRET
```

```csharp
using System.Security.Claims;
using Nine.AspNetCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddNineWebApp();
builder.Services.AddAuthorization();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapNineWebApp(); // /nine/login, /nine/signup, /nine/logout; the callback is /nine/callback

app.MapGet("/dashboard", (ClaimsPrincipal user) => $"Signed in as {user.FindFirstValue("email")}")
    .RequireAuthorization();

app.Run();
```

`AddNineWebApp` sets up ASP.NET Core's cookie and OpenID Connect handlers for 9in: PKCE, the `iss` check, ID tokens verified with every algorithm of the key library (EdDSA included), `client_secret_basic`, and the access token refreshed, with rotation, before it expires. Link to `/nine/login?return_to=/dashboard`, `/nine/signup` and `/nine/logout`; in MVC, `[Authorize]` works as usual. `await HttpContext.GetNineAccessTokenAsync()` returns the access token for your API.

| Route | When signed out |
|---|---|
| A page with `RequireAuthorization()` or `[Authorize]` | Browsers go to the 9in sign-in page and come back; API calls get 401 |
| `/nine/logout?return_to=/` | Revokes the refresh token and ends the session here and at 9in (`local=1`: here only) |

Protect an API in the same app or its own:

```csharp
builder.Services.AddAuthentication().AddNineApi(); // Nine:ApiAudience, or Nine:Audience

app.MapGet("/api/orders", (ClaimsPrincipal user) => user.FindFirstValue("sub"))
    .RequireScope("orders:read");   // [RequireScope("orders:read")] on MVC controllers
```

With the client ID and secret set, tokens are verified in **hybrid** mode (a local check, then one cached introspection, kept in your `IDistributedCache`), and `app.MapNineWebhooks()` drops cached answers when `token.revoked`, `session.revoked` or `user.*` events arrive; set `Nine:WebhookSecret` and subscribe that URL (`/nine/webhook`) in the console. `app.MapNineAdapter<MyUsers>()` serves the [adapter protocol](https://9in.io/docs/own-database/) for your own user database.

## Any .NET app

```bash
dotnet add package 9in
```

```csharp
using Nine;

var auth = new AuthClient(AuthClientOptions.FromEnvironment()); // NINE_ISSUER, NINE_CLIENT_ID, NINE_CLIENT_SECRET, NINE_REDIRECT_URI

// /nine/login
var login = await auth.CreateLoginAsync(new LoginOptions { ReturnTo = "/dashboard" });   // Screen = LoginScreen.SignUp for the sign-up form
// keep login.Pending.ToJson() in the session, redirect to login.Url

// /nine/callback: checks state and iss, exchanges the code, verifies the ID token
var tokens = await auth.HandleCallbackAsync(callbackUrl, PendingLogin.FromJson(saved));

// later
tokens = await auth.EnsureFreshAsync(tokens);   // refreshes (and rotates)

// /nine/logout
await auth.RevokeAsync(tokens.RefreshToken!);
var url = await auth.GetLogoutUrlAsync(tokens.IdToken, "https://app.acme.com/");
```

The same package has `TokenVerifier` and `HybridTokenVerifier` for APIs, `ManagementClient`, webhook verification with `EventDeduplicator`, an adapter handler, client credentials (`AddNineClientCredentials()` on an `HttpClient` in ASP.NET Core) and the [device flow](https://9in.io/docs/devices/) for CLIs (`StartDeviceAuthorizationAsync`).

## Without the 9in packages

```csharp
builder.Services.AddAuthentication(o => { o.DefaultScheme = "Cookies"; o.DefaultChallengeScheme = "oidc"; })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", o =>
    {
        o.Authority = "https://acme.9in.io";
        o.ClientId = "app_…";
        o.ClientSecret = builder.Configuration["Nine:ClientSecret"];
        o.ResponseType = "code";
        o.SaveTokens = true;
        o.MapInboundClaims = false;
        o.CallbackPath = "/nine/callback";
    });
```

The stock handler doesn't refresh tokens, and Microsoft.IdentityModel has no Ed25519 support, so keep an RSA or EC default signing key with it (or use the 9in package, which verifies every algorithm).
