---
title: "sdk/rust"
description: "네트워크 호출 없는 JWT 검증, 요청 인증, webhook 서명 검증을 지원하는 비동기 Rust 서버 SDK."
locale: "ko"
---

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

# sdk/rust

## 상태

로컬에서 구현 및 검증되었습니다. 실제 IdP 왕복 검증(JWKS 가져오기, 실제 XID 인스턴스에 대한 토큰 서명/검증)은 아직 수행되지 않았으며 프로덕션 사용 전에 완료되어야 합니다.

## 설치

`Cargo.toml`에 추가하세요:

```toml
[dependencies]
xid = "0.1"
tokio = { version = "1", features = ["full"] }
```

## 빠른 시작

```rust
use std::sync::Arc;
use xid::{XidClient, XidClientConfig, AuthState};

#[tokio::main]
async fn main() {
let config = XidClientConfig::new("https://xid.dev")
    .with_audience("your-client-id");

let client = Arc::new(XidClient::new(config).expect("build client"));

match client.verify_token("eyJ...").await {
    Ok(verified) => {
        println!("user: {}", verified.claims.sub);
        println!("email: {:?}", verified.claims.email);
    }
    Err(e) => eprintln!("invalid token: {e}"),
}
}
```

## 요청 인증

```rust
let state = client.authenticate_request(raw_headers, cookies).await;

match state {
AuthState::Authenticated(token) => {
    println!("user: {}", token.claims.sub);
    // token.claims.has_scope("openid") -> bool
    // token.claims.org_id -> Option<String>
}
AuthState::Unauthenticated => { /* return 401 */ }
AuthState::Invalid(e) => { /* return 401 */ }
}
```

## webhook 검증

```rust
use xid::WebhookVerifier;

let webhook_secret =
std::env::var("XID_WEBHOOK_SECRET").expect("XID_WEBHOOK_SECRET is required");
let verifier = WebhookVerifier::new(&webhook_secret).expect("valid secret");

match verifier.verify_from_headers(headers, body) {
Ok(()) => {
    let payload = xid::WebhookPayload::from_bytes(body).unwrap();
    println!("event: {}", payload.event_type);
}
Err(e) => { /* return 400 */ }
}
```

## 핵심 API

| 심볼 | 설명 |
| --- | --- |
| `XidClientConfig::new(issuer)` | 최소 생성자. 선택적 설정을 위해 빌더 메서드를 체이닝하세요. |
| `.with_audience(aud)` | 예상 audience 클레임을 설정합니다. |
| `.with_session_cookie(name)` | 세션 cookie 이름을 재정의합니다(기본값 `__session`). |
| `.with_leeway(seconds)` | exp/nbf에 대한 클럭 편차 허용 범위. |
| `XidClient::new(config)` | 기본 reqwest HTTP 클라이언트로 클라이언트를 빌드합니다. |
| `XidClient::with_http_client(config, http)` | 사용자 정의 reqwest 클라이언트로 클라이언트를 빌드합니다(테스트에 유용). |
| `client.verify_token(token)` | 토큰 문자열을 검증합니다; `XidResult<VerifiedToken>`를 반환합니다. |
| `client.authenticate_request(headers, cookies)` | 원시 헤더와 cookie에서 토큰을 추출하고 검증합니다; `AuthState`를 반환합니다. |
| `WebhookVerifier::new(secret)` | `whsec_<base64>` 또는 일반 base64 시크릿을 허용합니다. |
| `verifier.verify_from_headers(headers, body)` | svix 헤더를 자동으로 추출하고 HMAC-SHA256 서명을 검증합니다. |

## 플랫폼 참고 사항

- tokio 기반 비동기 우선 API. reqwest를 통해 rustls를 사용하며 OpenSSL에 의존하지 않습니다.
- ES256이 기본 알고리즘입니다. RS256이 지원됩니다. PS256 지원이 계획되어 있습니다. ES384/ES512는 아직 구현되지 않았습니다.
- 프레임워크 통합 기능(`axum`, `actix-web`)은 계획되어 있지만 이번 릴리스에는 포함되지 않습니다.
- `XidError`는 `thiserror`를 사용하며 `JwtValidation`, `JwksFetch`, `KeyNotFound`, `IssuerMismatch` 및 webhook 전용 변형을 포함한 구조적 오류 변형을 제공합니다.

Source: https://xid.dev/ko/sdks/rust/index.mdx
