---
title: "sdk/dotnet"
description: "SDK de servidor .NET 8 para verificação JWT sem rede, autenticação derequisições ASP.NET Core e validação de assinatura de webhook."
locale: "pt-BR"
---

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

# sdk/dotnet

## Estado

Implementado e verificado localmente. A verificação de ida e voltacom um IdP real (busca de JWKS, assinatura/verificação de tokencontra uma instância XID ativa) ainda não foi realizada e deve serconcluída antes do uso em produção.

## Instalar

Requer target .NET 8.

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

## Configuração ASP.NET Core (recomendado)

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

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

## Autentica uma requisição

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

## Verifica o token diretamente

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

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

| Propriedade | Padrão | Descrição |
| --- | --- | --- |
| `Issuer` | obrigatório | URL do emissor XID |
| `Audience` | `null` | Claim aud esperado; null ignora a validação |
| `JwksTtl` | 1 hora | TTL do cache em memória do JWKS |
| `SessionCookieName` | `__session` | Nome de cookie de fallback para extração de token |
| `ClockSkew` | 5 minutos | Tolerância de desvio de relógio JWT para exp/nbf |
| `WebhookToleranceWindow` | 5 minutos | Janela de prevenção de replay de webhook |

## API do XidClient

| Método | Descrição |
| --- | --- |
| `VerifyTokenAsync(token, ct)` | Verifica string JWT; lança `TokenVerificationException` em casode falha. |
| `AuthenticateRequestAsync(authHeader, cookies, ct)` | Extrai e verifica o token; retorna `AuthStatus`; não lançaexceções. |
| `VerifyWebhook(payload, headers, secret)` | Valida a assinatura do webhook; lança`WebhookVerificationException` em caso de falha. Síncrono. |

## Notas da plataforma

- Usa `Microsoft.IdentityModel.Tokens` e`System.IdentityModel.Tokens.Jwt` 8.x. ES256 é primário; RS256 ePS256 são suportados.
- `AddXid()` registra `XidClient` como singleton e conecta`IHttpClientFactory` para busca de JWKS.
- Hierarquia de exceções: `XidException` -&gt; `JwksException`,`TokenVerificationException`,`WebhookVerificationException`.

Source: https://xid.dev/pt-br/sdks/dotnet/index.mdx
