---
title: "sdk/dotnet"
description: "SDK de servidor .NET 8 para verificación JWT sin llamadas de red, autenticación de solicitudes ASP.NET Core y validación de firma de webhook."
locale: "es"
---

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

# sdk/dotnet

## Estado

Implementado y verificado localmente. La verificación de ida y vuelta contra un IdP real (obtención de JWKS, firma/verificación de tokens contra una instancia XID en producción) aún no se ha realizado y debe completarse antes del uso en producción.

## Instalación

Se requiere .NET 8 como destino.

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

## Configuración de ASP.NET Core (recomendado)

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

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

## Autenticar una solicitud

```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 });
}
}
```

## Verificar token directamente

```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}");
}
```

## Verificar 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

| Propiedad | Por defecto | Descripción |
| --- | --- | --- |
| `Issuer` | obligatorio | URL del emisor XID |
| `Audience` | `null` | Claim aud esperado; null omite la validación |
| `JwksTtl` | 1 hora | TTL del caché en memoria de JWKS |
| `SessionCookieName` | `__session` | Nombre de cookie de reserva para extraer el token |
| `ClockSkew` | 5 minutos | Tolerancia de desfase de reloj JWT para exp/nbf |
| `WebhookToleranceWindow` | 5 minutos | Ventana de prevención de repetición del webhook |

## API de XidClient

| Método | Descripción |
| --- | --- |
| `VerifyTokenAsync(token, ct)` | Verifica una cadena JWT; lanza `TokenVerificationException` al fallar. |
| `AuthenticateRequestAsync(authHeader, cookies, ct)` | Extrae y verifica el token; devuelve `AuthStatus`; no lanza excepciones. |
| `VerifyWebhook(payload, headers, secret)` | Valida la firma del webhook; lanza `WebhookVerificationException` al fallar. Síncrono. |

## Notas de plataforma

- Usa `Microsoft.IdentityModel.Tokens` y `System.IdentityModel.Tokens.Jwt` 8.x. ES256 es el principal; RS256 y PS256 están soportados.
- `AddXid()` registra `XidClient` como singleton y conecta `IHttpClientFactory` para obtener el JWKS.
- Jerarquía de excepciones: `XidException` -&gt; `JwksException`, `TokenVerificationException`, `WebhookVerificationException`.

Source: https://xid.dev/es/sdks/dotnet/index.mdx
