---
title: "sdk/dotnet"
description: ".NET 8 服务端 SDK，提供 networkless JWT 验证、ASP.NET Core 请求认证和 webhook 签名校验。"
locale: "zh-Hans"
---

> Documentation Index
> Fetch the locale documentation index at: https://xid.dev/zh-hans/llms.txt
> Use this file to discover all available pages before exploring further.

# sdk/dotnet

## 状态

已在本地实现并验证。针对真实 XID 实例的 IdP 往返验证（JWKS 获取、token 签名/验证）尚未执行，生产使用前必须完成。

## 安装

需要 .NET 8 目标框架。

```xml
<PackageReference Include="Xid" Version="0.1.0" />
```

## ASP.NET Core 配置（推荐）

```csharp
// Program.cs
using Xid;

builder.Services.AddXid(options =>
{
options.Issuer   = "https://xid.dev";
options.Audience = "your-client-id"; // optional
});
```

## 认证请求

```csharp
// Controller / Minimal API
public class MyController(XidClient xid) : ControllerBase
{
[HttpGet("/me")]
public async Task<IActionResult> GetMe()
{
    var auth = await xid.AuthenticateRequestAsync(
        authorizationHeader: Request.Headers.Authorization,
        cookies: Request.Cookies.ToDictionary(c => c.Key, c => c.Value));

    if (!auth.Authenticated)
        return Unauthorized(auth.Reason);

    return Ok(new { sub = auth.Claims!.Sub, email = auth.Claims.Email });
}
}
```

## 直接验证 token

```csharp
using Xid;

var client = new XidClient(new XidOptions { Issuer = "https://xid.dev" });

try
{
var claims = await client.VerifyTokenAsync("eyJ...");
Console.WriteLine($"sub={claims.Sub} email={claims.Email}");
}
catch (TokenVerificationException ex)
{
Console.WriteLine($"Invalid token: {ex.Message}");
}
```

## 验证 webhook

```csharp
app.MapPost("/webhooks/xid", async (HttpRequest req, XidClient xid) =>
{
using var ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
var body = ms.ToArray();

var headers = new Dictionary<string, string>
{
    ["svix-id"]        = req.Headers["svix-id"].ToString(),
    ["svix-timestamp"] = req.Headers["svix-timestamp"].ToString(),
    ["svix-signature"] = req.Headers["svix-signature"].ToString(),
};

var webhookSecret = Environment.GetEnvironmentVariable("XID_WEBHOOK_SECRET")
    ?? throw new InvalidOperationException("XID_WEBHOOK_SECRET is required");

try
{
    var webhook = xid.VerifyWebhook(body, headers, secret: webhookSecret);
    return Results.Ok();
}
catch (WebhookVerificationException ex)
{
    return Results.BadRequest(ex.Message);
}
});
```

## XidOptions

| 属性 | 默认 | 描述 |
| --- | --- | --- |
| `Issuer` | 必填 | XID 签发方 URL |
| `Audience` | `null` | 期望的 aud claim；null 跳过验证 |
| `JwksTtl` | 1 小时 | JWKS 内存缓存 TTL |
| `SessionCookieName` | `__session` | 提取 token 的回退 cookie 名称 |
| `ClockSkew` | 5 分钟 | JWT exp/nbf 时钟偏差容忍度 |
| `WebhookToleranceWindow` | 5 分钟 | Webhook 重放防护窗口 |

## XidClient API

| 方式 | 描述 |
| --- | --- |
| `VerifyTokenAsync(token, ct)` | 验证 JWT 字符串；失败时抛出 `TokenVerificationException`。 |
| `AuthenticateRequestAsync(authHeader, cookies, ct)` | 提取并验证 token；返回 `AuthStatus`；不抛出异常。 |
| `VerifyWebhook(payload, headers, secret)` | 校验 webhook 签名；失败时抛出 `WebhookVerificationException`。同步执行。 |

## 平台注意事项

- 使用 `Microsoft.IdentityModel.Tokens` 和 `System.IdentityModel.Tokens.Jwt` 8.x。ES256 为主要算法；支持 RS256 和 PS256。
- `AddXid()` 将 `XidClient` 注册为单例，并接入 `IHttpClientFactory` 用于 JWKS 获取。
- 异常层级：`XidException` -&gt; `JwksException`、`TokenVerificationException`、`WebhookVerificationException`。

Source: https://xid.dev/zh-hans/sdks/dotnet/index.mdx
