---
title: "sdk/ruby"
description: "Ruby 服务端 SDK，提供 networkless JWT 验证、Rack/Rails 请求认证和 webhook 签名校验。"
locale: "zh-Hans"
---

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

# sdk/ruby

## 状态

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

## 安装

```ruby
# Gemfile
gem "xid"

bundle install
```

## 快速开始

```ruby
require "xid"

Xid.configure do |c|
  c.issuer         = "https://xid.dev"
  c.audience       = "your_client_id"
  c.webhook_secret = "whsec_AbCdEf..."
end

# Verify a token
begin
  claims = Xid.verify_token(raw_token)
  puts claims.sub    # => "usr_abc123"
  puts claims.scope  # => "openid profile email"
rescue Xid::TokenVerificationError => e
  puts "Token invalid: #{e.message}"
end
```

## 认证 Rack/Rails 请求

```ruby
# Sinatra before-filter
before do
  auth = Xid.authenticate_request(request)
  halt 401, "Unauthorized" unless auth.signed_in?
  @current_user_id = auth.claims.sub
end

# Rack middleware (env-based)
auth = Xid.authenticate_request(env)
unless auth.signed_in?
  return [401, { "Content-Type" => "application/json" },
      [JSON.generate({ error: auth.reason })]]
end
```

## 验证 webhook

```ruby
# Rails controller action
def receive
  raw_body = request.raw_post
  payload = Xid.verify_webhook(request.headers.to_h, raw_body)
  handle_event(payload["type"], payload["data"])
  head :ok
rescue Xid::WebhookVerificationError
  head :bad_request
end
```

## 多签发方配置

```ruby
config_a = Xid::Configuration.new
config_a.issuer   = "https://tenant-a.xid.dev"
config_a.audience = "client_a"
client_a = Xid::Client.new(config_a)
claims = client_a.verify_token(token)
```

## 配置选项

| 密钥 | 默认 | 描述 |
| --- | --- | --- |
| `issuer` | `https://xid.dev` | OIDC 签发方 URL |
| `audience` | `nil` | 期望的 aud claim；nil 跳过验证 |
| `jwks_ttl` | `3600` | JWKS 本地缓存 TTL（秒） |
| `leeway` | `60` | JWT 时钟偏差容忍度（秒） |
| `webhook_secret` | `nil` | 带 `whsec_` 前缀的 Webhook 签名密钥 |
| `webhook_tolerance` | `300` | Webhook 重放窗口（秒） |
| `cookie_name` | `__xid_token` | 提取访问令牌的 cookie key |

## 平台注意事项

- 依赖 `jwt` gem（支持 ES256/RS256）。需要 Ruby 3.1+。
- `Xid.authenticate_request` 接受 Rack env 哈希和 Rack `Request` 对象两种形式。
- 异常层级：`Xid::Error` -&gt; `ConfigurationError`、`JwksError`、`TokenVerificationError`、`WebhookVerificationError`。

Source: https://xid.dev/zh-hans/sdks/ruby/index.mdx
