---
title: "sdk/go"
description: "SDK de servidor Go para verificación JWT sin llamadas de red, autenticación de solicitudes 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/go

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

```shell
go get github.com/StringKe/xid/sdk/go
```

## Inicio rápido

Crea un único `Client` al arrancar la aplicación y reutilízalo entre solicitudes. El cliente almacena el JWKS en caché internamente con un TTL configurable.

```go
import "github.com/StringKe/xid/sdk/go/xid"

client, err := xid.NewClient(xid.ClientOptions{
Issuer:        "https://xid.dev",
Audience:      "your-client-id",
WebhookSecret: "whs_...",
})
if err != nil {
log.Fatal(err)
}

// HTTP middleware (recommended)
http.Handle("/api/", client.Middleware(apiHandler, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
}))

// Inside a protected handler
func apiHandler(w http.ResponseWriter, r *http.Request) {
claims := xid.ClaimsFromContext(r.Context())
fmt.Fprintf(w, "hello %s", claims.Subject)
}
```

## Verificar token directamente

```go
claims, err := client.VerifyAccessToken(ctx, tokenString)
if err != nil {
// handle verification failure
}
fmt.Println(claims.Subject, claims.OrgID)
```

## Verificar webhook

```go
func webhookHandler(w http.ResponseWriter, r *http.Request) {
event, err := client.VerifyWebhook(r)
if err != nil {
    http.Error(w, "invalid signature", http.StatusBadRequest)
    return
}
// event.Body: raw JSON body
// event.ID:   svix-id for idempotency
w.WriteHeader(http.StatusNoContent)
}
```

## API principal

| Símbolo | Descripción |
| --- | --- |
| `NewClient(opts)` | Construye el cliente. `Issuer` es obligatorio; los demás campos son opcionales. |
| `(*Client).VerifyAccessToken(ctx, token)` | Verifica una cadena JWT y devuelve `*Claims` o un error. |
| `(*Client).AuthenticateRequest(ctx, r)` | Extrae y verifica el token de una solicitud HTTP. Siempre devuelve `AuthState`, no entra en pánico. |
| `(*Client).Middleware(next, onUnauthorized)` | Middleware estándar de `net/http`. Inyecta `*Claims` en el contexto al tener éxito. |
| `ClaimsFromContext(ctx)` | Extrae los claims inyectados por el Middleware. |
| `(*Client).VerifyWebhook(r)` | Verifica la firma de la solicitud del webhook. Devuelve `*WebhookEvent` con el cuerpo sin procesar al tener éxito. |

## ClientOptions

| Campo | Por defecto | Descripción |
| --- | --- | --- |
| `Issuer` | obligatorio | URL del emisor XID |
| `Audience` | vacío (omitir) | Claim aud de JWT esperado |
| `WebhookSecret` | vacío | Secreto de firma HMAC del webhook |
| `JWKSCacheTTL` | `1h` | TTL del caché local de JWKS |
| `HTTPClient` | tiempo de espera predeterminado: 10 s | Cliente HTTP para obtener el JWKS |

## Notas de plataforma

- ES256 es el algoritmo principal; RS256 está soportado por compatibilidad. ES384 y ES512 aún no están implementados.
- El JWKS se obtiene de `{issuer}/jwks`. La detección automática de OIDC Discovery es una mejora planificada.
- `Claims` integra `jwt.RegisteredClaims` y añade `ClientID`, `Scope`, `AMR`, `ACR`, `OrgID`, `OrgSlug`.

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