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

# 認証

TypeScript SDK は、さまざまなユースケースに応じて複数の認証方式をサポートしています。

<div id="bearer-token-app-only-auth">
  ## ベアラートークン (App-Only 認証)
</div>

読み取り専用の操作や公開データにアクセスする場合は、次のようにします:

<CodeGroup dropdown>
  ```typescript quickstart.ts theme={null} theme={null}
  import { 
    Client, 
    type ClientConfig,
    type Users
  } from '@xdevplatform/xdk';

  const config: ClientConfig = { bearerToken: 'your-bearer-token' };

  const client: Client = new Client(config);

  async function main(): Promise<void> {
    const userResponse: Users.GetByUsernameResponse = await client.users.getByUsername('XDevelopers');
    const username: string = userResponse.data?.username!;
    console.log(username);
  }

  main();
  ```

  ```javascript quickstart.js theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: 'your-bearer-token' });

  const userResponse = await client.users.getByUsername('XDevelopers');
  const username = userResponse.data.username;
  console.log(username);
  ```
</CodeGroup>

<div id="oauth-10a-user-context">
  ## OAuth 1.0a (ユーザーコンテキスト)
</div>

レガシーアプリケーションや特定のユースケース向けです。

<CodeGroup dropdown>
  ```typescript oauth1.ts theme={null} theme={null}
  import { 
    Client, 
    OAuth1,
    type OAuth1Config,
    type ClientConfig,
    type Users
  } from '@xdevplatform/xdk';

  const oauth1Config: OAuth1Config = {
    apiKey: 'your-api-key',
    apiSecret: 'your-api-secret',
    accessToken: 'user-access-token',
    accessTokenSecret: 'user-access-token-secret'
  };

  const oauth1: OAuth1 = new OAuth1(oauth1Config);

  const config: ClientConfig = {
    oauth1: oauth1,
  };

  const client: Client = new Client(config);

  async function main(): Promise<void> {
    const response: Users.GetMeResponse = await client.users.getMe();

    const me = response.data;
    console.log(me);
  }

  main();

  ```

  ```javascript oauth1.js theme={null} theme={null}
  import { Client, OAuth1 } from '@xdevplatform/xdk';

  const oauth1 = new OAuth1({
    apiKey: 'your-api-key',
    apiSecret: 'your-api-secret',
    accessToken: 'user-access-token',
    accessTokenSecret: 'user-access-token-secret'
  });

  const client = new Client({ oauth1: oauth1 });

  const response = await client.users.getMe();
  const me = response.data;
  console.log(me);

  ```
</CodeGroup>

<div id="oauth-20-user-context">
  ## OAuth 2.0（ユーザーコンテキスト）
</div>

ユーザーコンテキストで操作を行う場合:

<CodeGroup dropdown>
  ```typescript oauth2.ts theme={null} theme={null}
  import { 
    Client, 
    OAuth2,
    generateCodeVerifier,
    generateCodeChallenge,
    type OAuth2Config,
    type ClientConfig,
    type OAuth2Token
  } from '@xdevplatform/xdk';

  (async (): Promise<void> => {
    const oauth2Config: OAuth2Config = {
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
      redirectUri: 'https://example.com',
      scope: ['tweet.read', 'users.read', 'offline.access'],
    };

    const oauth2: OAuth2 = new OAuth2(oauth2Config);

    const state: string = 'example-state';
    const codeVerifier: string = generateCodeVerifier();
    const codeChallenge: string = await generateCodeChallenge(codeVerifier);
    
    oauth2.setPkceParameters(codeVerifier, codeChallenge);
    
    const authUrl: string = await oauth2.getAuthorizationUrl(state);

    // ユーザーが authUrl にアクセスしてアプリを承認する
    // 承認後、ユーザーは code パラメータ付きでリダイレクトされる
    // コールバック URL（例: クエリパラメータ）から code を取得する
    const authCode: string = 'code-from-callback-url'; // OAuth コールバックから取得した実際のコードに置き換える

    const tokens: OAuth2Token = await oauth2.exchangeCode(authCode, codeVerifier);

    const config: ClientConfig = {
      accessToken: tokens.access_token,
    };

    const client: Client = new Client(config);
  });

  ```

  ```javascript oauth2.js theme={null} theme={null}
  import { Client, OAuth2, generateCodeVerifier, generateCodeChallenge } from '@xdevplatform/xdk';

  (async () => {
    const oauth2 = new OAuth2({
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
      redirectUri: 'https://example.com',
      scope: ['tweet.read', 'users.read', 'offline.access'],
    });

    const state = 'example-state';
    const codeVerifier = generateCodeVerifier();
    const codeChallenge = await generateCodeChallenge(codeVerifier);
    oauth2.setPkceParameters(codeVerifier, codeChallenge);
    const authUrl = await oauth2.getAuthorizationUrl(state);

    // ユーザーが authUrl にアクセスしてアプリを承認する
    // 承認後、ユーザーは code パラメータ付きでリダイレクトされる
    // コールバック URL（例: クエリパラメータ）から code を取得する
    const authCode = 'code-from-callback-url'; // OAuth コールバックから取得した実際のコードに置き換える

    const tokens = await oauth2.exchangeCode(authCode, codeVerifier);

    const client = new Client({ accessToken: tokens.access_token });

    const response = await client.users.getMe();
    const me = response.data;
    console.log(me);
  });
  ```
</CodeGroup>

<div id="environment-variables">
  ## 環境変数
</div>

機密性の高い認証情報は環境変数に保存してください。

```bash theme={null}
# .env
X_API_BEARER_TOKEN=your-bearer-token
X_API_CLIENT_ID=your-client-id
X_API_CLIENT_SECRET=your-client-secret
```

<CodeGroup dropdown>
  ```typescript env.ts theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: process.env.X_API_BEARER_TOKEN });
  ```

  ```javascript env.js theme={null} theme={null}
  import { Client } from '@xdevplatform/xdk';

  const client = new Client({ bearerToken: process.env.X_API_BEARER_TOKEN });
  ```
</CodeGroup>

<Info>
  JavaScript/TypeScript 向け XDK を使用した、より詳細なコードサンプルについては、[コードサンプルの GitHub リポジトリ](https://github.com/xdevplatform/samples/tree/main/javascript) を参照してください。
</Info>
