跳到正文

sdk/go

Go 服务端 SDK,提供 networkless JWT 验证、请求认证和 webhook 签名校验。

状态

已在本地实现并验证。针对真实 XID 实例的 IdP 往返验证(JWKS 获取、token 签名/验证)尚未执行,生产使用前必须完成。

Registry 状态:UNPUBLISHED。此 SDK 只能从仓库源码 checkout 安装;不要使用外部 package registry。

请求认证默认仅接受 Bearer。只有配置精确名称时才读取应用自有 JWT cookie。SDK 绝不扫描或本地验证 opaque __Host-xid.rt.* Core cookie;应将完整 Cookie header 转发到 exact same-origin POST /v1/sessions/token,并禁用 redirect,且只接受仅包含 token 字段的响应。

安装

go get github.com/StringKe/xid/sdk/go@main

快速开始

在应用启动时创建一个 Client 并在请求间复用。客户端以可配置 TTL 在内部缓存 JWKS。

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

直接验证 token

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

// Explicit same-origin Core session -> JWT exchange
token, err := client.ExchangeSessionToken(
    ctx,
    "https://app.example.com/account",
    request.Header.Get("Cookie"),
    "/v1/sessions/token",
)

验证 webhook

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

符号 描述
NewClient(opts) 构建客户端。Issuer 必填;其他字段可选。
(*Client).VerifyAccessToken(ctx, token) 验证 JWT 字符串,返回 *Claims 或错误。
(*Client).AuthenticateRequest(ctx, r) 从 HTTP 请求中提取并验证 token。始终返回 AuthState,不会 panic。
(*Client).Middleware(next, onUnauthorized) 标准 net/http middleware。成功时将 *Claims 注入 context。
ClaimsFromContext(ctx) 提取由 Middleware 注入的 claims。
(*Client).VerifyWebhook(r) 验证 webhook 请求签名。成功时返回带原始请求体的 *WebhookEvent。

ClientOptions

字段 默认 描述
Issuer 必填 XID 签发方 URL
Audience 空(跳过) 期望的 JWT aud claim
WebhookSecret 空 Webhook HMAC 签名密钥
JWKSCacheTTL 1h JWKS 本地缓存 TTL
HTTPClient 默认 10 秒超时 用于 JWKS 获取的 HTTP 客户端

平台注意事项

  • ES256 为主要算法;支持 RS256 以兼容旧版本。ES384 和 ES512 尚未实现。
  • JWKS 从 {issuer}/jwks 获取。OIDC Discovery 自动检测是计划中的改进。
  • Claims 嵌入 jwt.RegisteredClaims 并添加 ClientID、Scope、AMR、ACR、OrgID、OrgSlug。
导航

输入内容以搜索...

使用方向键导航按 Enter 键选择按 Escape 键关闭