> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 認証

> Python XDK を Bearer Token、OAuth 2.0 PKCE、または OAuth 1.0a ユーザーコンテキストで認証し、X API エンドポイントを呼び出したりユーザーの代わりに投稿したりします。

X API はすべてのエンドポイントで認証が必要です。XDK は次の 3 つの認証方式をサポートしています:

1. Bearer Token（アプリのみ）
2. PKCE 付き OAuth 2.0
3. OAuth 1.0a（ユーザーコンテキスト）

* **Bearer Token**: アプリ認証に対応するエンドポイントで、読み取り専用アクセスに使用します（投稿の検索、ストリーミングエンドポイントなど）。
* **OAuth 2.0 PKCE**: スコープに基づき、ユーザーが認可したアクセス（例: 認証済みユーザーの非公開の投稿メトリクスを取得）向けの安全な認証です。
* **OAuth 1.0a**: ユーザー固有の操作向けのレガシー認証です（ユーザーの代わりに投稿する、リストを管理するなど）。
  認証情報は [X Developer Console](https://developer.x.com/en/portal/dashboard) から取得します。承認済みの開発者アカウントと、適切な権限（Read + Write など）を持つアプリが必要です。

## クライアントの作成

どの認証フローも `Client` インスタンスを作成します:

```python theme={null}
from xdk import Client
```

### 1. Bearer Token（アプリのみ）

ユーザーコンテキストを伴わない読み取り専用の操作向けです。
**手順**:

1. Developer Console でアプリの Bearer Token を生成します。
2. それを `Client` に渡します。
   **例**:

```python theme={null}
client = Client(bearer_token="XXXXX")
```

**使い方**:

```python theme={null}
# search_recent returns an Iterator, so iterate over it
for page in client.posts.search_recent(query="python", max_results=10):
    if page.data and len(page.data) > 0:
        first_post = page.data[0]
        post_text = first_post.text if hasattr(first_post, 'text') else first_post.get('text', '')
        print(post_text)  # Access first Post
        break
```

### 2. PKCE 付き OAuth 2.0（ユーザーコンテキスト）

この例では、Proof Key for Code Exchange（PKCE）付きの OAuth 2.0 を使う方法を示します。ユーザー固有のアクセス（ユーザーの代わりに投稿する、ユーザーのためにメディアをアップロードするなど）に使用します。
**手順**:

1. Developer Console で、リダイレクト URI（例: `http://localhost:8080/callback`）を指定してアプリを登録します。
2. Client ID を取得します（PKCE ではシークレットは不要です）。
3. フローを開始し、ユーザーを認可 URL に誘導し、コールバックを処理します。
   **例**（コールバック用の Web サーバーを使用）:

```python title="Example" expandable lines wrap icon="python" theme={null}
from xdk.oauth2_auth import OAuth2PKCEAuth
from urllib.parse import urlparse
import webbrowser
# Step 1: Create PKCE instance
auth = OAuth2PKCEAuth(
    client_id="YOUR_CLIENT_ID",
    redirect_uri="YOUR_CALLBACK_URL",
    scope="tweet.read users.read offline.access"
)
# Step 2: Get authorization URL
auth_url = auth.get_authorization_url()
print(f"Visit this URL to authorize: {auth_url}")
webbrowser.open(auth_url)
# Step 3: Handle callback (in a real app, use a web framework like Flask)
# Assume callback_url = "http://localhost:8080/callback?code=AUTH_CODE_HERE"
callback_url = input("Paste the full callback URL here: ")
# Step 4: Exchange code for tokens
tokens = auth.fetch_token(authorization_response=callback_url)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]  # Store for renewal
# Step 5: Create client
# Option 1: Use bearer_token (OAuth2 access tokens work as bearer tokens)
client = Client(bearer_token=access_token)
# Option 2: Pass the full token dict for automatic refresh support
# client = Client(token=tokens)
```

**トークンの更新**（長時間セッションでは SDK が自動的に処理）:

```python theme={null}
# If access token expires, refresh using stored refresh_token
# The refresh_token method uses the stored token from the OAuth2PKCEAuth instance
tokens = auth.refresh_token()
# Use the refreshed token
client = Client(bearer_token=tokens["access_token"])
# Or pass the full token dict: client = Client(token=tokens)
```

### 3. OAuth 1.0a（ユーザーコンテキスト）

OAuth 1.0a 認証を必要とするレガシーアプリケーションや特定のユースケース向けです:
**手順**:

1. Developer Console で API Key と API Secret を取得します。
2. すでにアクセストークンを持っている場合はそのまま使用します。持っていない場合は OAuth 1.0a フローを実行して取得します。
3. OAuth1 インスタンスを作成し、Client に渡します。
   **例**（既存のアクセストークンを使用）:

```python title="Example" lines wrap icon="python" theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
# Step 1: Create OAuth1 instance with credentials
oauth1 = OAuth1(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    callback="http://localhost:8080/callback",
    access_token="YOUR_ACCESS_TOKEN",
    access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
# Step 2: Create client with OAuth1
client = Client(auth=oauth1)
# Step 3: Use the client
response = client.users.get_me()
me = response.data
print(me)
```

**例**（OAuth 1.0a フル フロー）:

```python title="Example" lines wrap icon="python" theme={null}
from xdk import Client
from xdk.oauth1_auth import OAuth1
import webbrowser
# Step 1: Create OAuth1 instance
oauth1 = OAuth1(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    callback="http://localhost:8080/callback"
)
# Step 2: Get request token
request_token = oauth1.get_request_token()
# Step 3: Get authorization URL
auth_url = oauth1.get_authorization_url(login_with_x=False)
print(f"Visit this URL to authorize: {auth_url}")
webbrowser.open(auth_url)
# Step 4: User authorizes and you receive oauth_verifier
# In a real app, handle this via callback URL
oauth_verifier = input("Enter the OAuth verifier from the callback: ")
# Step 5: Exchange for access token
access_token = oauth1.get_access_token(oauth_verifier)
# Step 6: Create client
client = Client(auth=oauth1)
# Now you can use the client
response = client.users.get_me()
```

**注意**:

* 本番環境ではシークレットをハードコーディングせず、環境変数やシークレットマネージャー（例: `os.getenv("X_BEARER_TOKEN")`）を使用してください。
* PKCE では、本番のリダイレクト URI は HTTPS にしてください。
* SDK はトークンを検証し、失敗時に `xdk.AuthenticationError` を発生させます。
  Python XDK を使った詳細なコードサンプルは、[コードサンプル GitHub リポジトリ](https://github.com/xdevplatform/samples/tree/main/python)を参照してください。
