---
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 relevant documentation index at: https://vonvon.id/pt-br/sdks/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 Vonvon ativa) ainda não foi realizada e deve serconcluída antes do uso em produção.

Status do registry: UNPUBLISHED. Instale este SDK somente a partir do checkout do código-fonte do repositório; não use um registry de pacotes externo.

A autenticação de requisições aceita somente Bearer por padrão. Um cookie JWT pertencente ao aplicativo só é lido quando seu nome exato é configurado. O cookie opaco do Core \_\_Host-vonvon.rt.\* nunca é pesquisado nem verificado localmente; troque-o encaminhando o header Cookie completo para o POST /v1/sessions/token da mesma origem exata, com redirects desativados, e aceite somente uma resposta que contenha apenas o campo token.

## Instalar

Requer target .NET 8.

```xml
<ItemGroup>
  <ProjectReference Include="../vonvon/sdk/dotnet/Vonvon.csproj" />
</ItemGroup>
```

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

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

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

## Autentica uma requisição

```csharp
// Controller / Minimal API
public class MyController(VonvonClient vonvon) : ControllerBase
{
[HttpGet("/me")]
public async Task<IActionResult> GetMe()
{
    var auth = await vonvon.AuthenticateRequestAsync(
        authorizationHeader: Request.Headers.Authorization);

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

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

private Task<string> ExchangeSessionAsync() => vonvon.ExchangeSessionTokenAsync(
    $"{Request.Scheme}://{Request.Host}{Request.Path}",
    Request.Headers.Cookie.ToString());
}
```

## Verifica o token diretamente

```csharp
using Vonvon;

var client = new VonvonClient(new VonvonOptions { Issuer = "https://vonvon.id" });

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/vonvon", async (HttpRequest req, VonvonClient vonvon) =>
{
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("VONVON_WEBHOOK_SECRET")
    ?? throw new InvalidOperationException("VONVON_WEBHOOK_SECRET is required");

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

## VonvonOptions

| Propriedade | Padrão | Descrição |
| --- | --- | --- |
| `Issuer` | obrigatório | URL do emissor Vonvon |
| `Audience` | `null` | Claim aud esperado; null ignora a validação |
| `JwksTtl` | 1 hora | TTL do cache em memória do JWKS |
| `SessionCookieName` | `disabled` | Nome do cookie JWT pertencente ao aplicativo; desativado salvo configuração explícita |
| `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 VonvonClient

| 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.
- `AddVonvon()` registra `VonvonClient` como singleton e conecta`IHttpClientFactory` para busca de JWKS.
- Hierarquia de exceções: `VonvonException` -&gt; `JwksException`,`TokenVerificationException`,`WebhookVerificationException`.

Source: https://vonvon.id/pt-br/sdks/dotnet/index.mdx
