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.
<PackageReference Include="Xid" Version="0.1.0" />Configuración de ASP.NET Core (recomendado)
// Program.cs
using Xid;
builder.Services.AddXid(options =>
{
options.Issuer = "https://xid.dev";
options.Audience = "your-client-id"; // optional
});Autenticar una solicitud
// 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
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
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.TokensySystem.IdentityModel.Tokens.Jwt8.x. ES256 es el principal; RS256 y PS256 están soportados. AddXid()registraXidClientcomo singleton y conectaIHttpClientFactorypara obtener el JWKS.- Jerarquía de excepciones:
XidException->JwksException,TokenVerificationException,WebhookVerificationException.