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

# 生成 JWT

> 生成用于单点登录 (SSO) 的 JSON Web Token (JWT)。

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

<PlansAvailable plans={["business"]} maxPackRequired={false} />

生成用于单点登录 (SSO) 的 JSON Web Token (JWT)。

更多细节请参阅 [Generate JWT 概览](/apis/profiles/generate-jwt-overview)。

<Note>
  JWT URL 的有效期为 **5 分钟**。5 分钟后必须重新生成 JWT URL。
  更多选项请参阅 Max Pack `expiresIn` 的[附加选项](/apis/profiles/generate-jwt-overview#jwt-expires-in)。
</Note>

## Header 参数

<HeaderAPI noProfileKey />

<ParamField header="X-Twitter-OAuth1-Api-Key" type="string">
  来自 X Developer Portal 的 X API Key(Consumer Key)。作为 `twitterApiKey` body 参数的替代方案。当提供该值时,生成的 JWT URL 将使用你自己的 X Developer App 进行 OAuth 关联。
</ParamField>

<ParamField header="X-Twitter-OAuth1-Api-Secret" type="string">
  来自 X Developer Portal 的 X API Secret(Consumer Secret)。作为 `twitterApiSecret` body 参数的替代方案。当提供 `X-Twitter-OAuth1-Api-Key` 时必填。
</ParamField>

<Info>
  \*\*推荐做法:\*\*通过 header 传递你的 X 凭据(`X-Twitter-OAuth1-Api-Key` 和 `X-Twitter-OAuth1-Api-Secret`),以与所有其他 Ayrshare API 端点保持一致。为了向后兼容,body 参数 `twitterApiKey` 和 `twitterApiSecret` 依然受支持。
</Info>

## Body 参数

<ParamField body="domain" type="string" required>
  应用的 domain。请使用开通 (onboarding) 时提供的完整 domain。
</ParamField>

<ParamField body="privateKey" type="string" required>
  用于加密的 Private Key。
</ParamField>

<ParamField body="profileKey" type="string" required>
  User Profile Key。此字段不可使用 API Key。
</ParamField>

<ParamField body="logout" type="boolean" default={false}>
  自动登出当前会话。不建议在生产环境中使用,因为会影响性能。

  更多信息请参阅[自动登出 Profile 会话](/multiple-users/api-integration-business#automatic-logout-of-a-profile-session)。
</ParamField>

<ParamField body="redirect" type="string">
  指定当点击 "Done" 按钮或 logo 图片时要跳转到的 URL。返回的 JWT URL 中该链接会被自动缩短。通过在 redirect URL 上添加查询参数 `origin=true`,可以[跳转原始 opener 窗口](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url)。
</ParamField>

<ParamField body="allowedSocial" type="array">
  指定在关联页面上要显示的社交网络。此设置会覆盖在[社交网络](/multiple-users/manage-user-profiles#set-social-networks-access)页面配置的社交网络。

  ```json Only display Facebook, X/Twitter, LinkedIn, and TikTok theme={"system"}
  {
    "allowedSocial": ["facebook", "twitter", "linkedin", "tiktok"]
  }
  ```
</ParamField>

<ParamField body="instagramLinkMethod" type="string">
  覆盖当用户在该 URL 对应的社交关联页面上点击 Instagram 按钮时所使用的 Instagram 关联流程。有效值:

  * `instagram`:直接使用 Instagram Login,无需 Facebook Page。
  * `facebook`:通过已关联的 Facebook Page 进行关联。

  ```json Force direct Instagram Login for this linking session theme={"system"}
  {
    "instagramLinkMethod": "instagram"
  }
  ```

  当省略该字段时,关联页面将使用你账户级别的 [Instagram Login](/multiple-users/manage-user-profiles#instagram-login) 设置。

  更多信息请参阅 [Instagram 关联方式](/apis/profiles/generate-jwt-overview#instagram-link-method)。
</ParamField>

<ParamField body="verify" type="boolean" default={false}>
  校验生成的 token 是否有效。建议仅在非生产环境中使用。

  更多信息请参阅[打开与关闭社交关联 URL](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url)。
</ParamField>

<ParamField body="base64" type="boolean" default={false}>
  如果 private key 是 base64 编码的,请设为 `true`。

  将 private.key 文件编码为 base64,并将单行字符串通过 `privateKey` 字段传入。

  例如在 Linux 上:`cat private.key | base64`
</ParamField>

<ParamField body="expiresIn" type="number" default={5}>
  以分钟为单位设置 token 的有效期。范围:1 分钟至 2880 分钟。

  更多信息请参阅 [JWT Expires In](/apis/profiles/generate-jwt-overview#jwt-expires-in)。
</ParamField>

<ParamField body="email" type="object" default={5}>
  发送一封 Connect Accounts 邮件,附带用户直接访问其社交关联页面的链接。

  更多信息请参阅 [Connect Accounts 邮件](/apis/profiles/generate-jwt-overview#connect-accounts-email)。
</ParamField>

<Info>
  当你提供 X API 凭据时,生成的 JWT URL 将使用你自己的 X Developer App 发起 OAuth 关联。你的终端用户会在 X 授权同意页面看到你的应用名称。
</Info>

<Warning>
  \*\*必需:\*\*在使用此功能之前,你必须在 X Developer App 的设置中(位于 Authentication settings > Callback URI / Redirect URL)添加以下回调 URL:

  * `https://profile.ayrshare.com/social-accounts`
  * `https://app.ayrshare.com/social-accounts`

  如果没有这些配置,OAuth 流程将失败并返回 `403 Callback URL not approved` 错误。
</Warning>

<RequestExample>
  ```javascript cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -H "X-Twitter-OAuth1-Api-Key: YOUR_CONSUMER_KEY" \
  -H "X-Twitter-OAuth1-Api-Secret: YOUR_CONSUMER_SECRET" \
  -d '{"domain": "ACME", "privateKey": "-----BEGIN RSA PRIVATE KEY...", "profileKey": "PROFILE_KEY"}' \
  -X POST https://api.ayrshare.com/api/profiles/generateJWT
  ```

  ```javascript JavaScript theme={"system"}
  const fs = require('fs');
  const API_KEY = "API_KEY";
  const PROFILE_KEY = "PROFILE_KEY";

  // Read in local private.key files - also can read from a DB
  const privateKey = fs.readFileSync('private.key', 'utf8');

  fetch("https://api.ayrshare.com/api/profiles/generateJWT", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${API_KEY}`,
          "X-Twitter-OAuth1-Api-Key": "YOUR_CONSUMER_KEY",
          "X-Twitter-OAuth1-Api-Secret": "YOUR_CONSUMER_SECRET"
        },
        body: JSON.stringify({
          domain: "ACME",          // required
          privateKey,              // required
          profileKey: PROFILE_KEY, // required
        }),
      })
        .then((res) => res.json())
        .then((json) => console.log(json))
        .catch(console.error);
  ```

  ```python Python theme={"system"}
  import requests

  # Read in local private.key files - also can read from a DB
  with open('.private.key') as f:
      profileKey = f.read()

  payload = {'domain': 'ACME',
          'privateKey': profileKey,
          'profileKey': 'PROFILE_KEY' }
  headers = {'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY',
          'X-Twitter-OAuth1-Api-Key': 'YOUR_CONSUMER_KEY',
          'X-Twitter-OAuth1-Api-Secret': 'YOUR_CONSUMER_SECRET'}

  r = requests.post('https://api.ayrshare.com/api/profiles/generateJWT',
      json=payload,
      headers=headers)

  print(r.json())
  ```

  ```php PHP theme={"system"}
  <?php
  require 'vendor/autoload.php';    // Composer auto-loader using Guzzle. See .../guzzlephp.org/en/stable/overview.html

  $client = new GuzzleHttp\Client();
  $res = $client->request(
      'POST',
      'https://api.ayrshare.com/api/post',
      [
          'headers' => [
              'Content-Type'  => 'application/json',
              'Authorization' => 'Bearer API_KEY'
          ],
          'json' => [
              'domain' => 'ACME',
              'privateKey' => '-----BEGIN RSA PRIVATE KEY...', // required
              'profileKey' => 'PROFILE_KEY', // requires
          ]
      ]
  );

  echo json_encode(json_decode($res->getBody()), JSON_PRETTY_PRINT);
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using System.IO;
  using Newtonsoft.Json;

  namespace GenerateJWTRequest_csharp
  {
    class GenerateJWT
    {
        static async Task Main(string[] args)
        {
            string API_KEY = "API_KEY";
            string url = "https://api.ayrshare.com/api/profiles/generateJWT";

            try
            {
                string privateKey = await File.ReadAllTextAsync("./private.key");

                var sendData = new
                {
                    domain = "domain",
                    privateKey = privateKey,
                    profileKey = "PROFILE_KEY"
                };

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + API_KEY);

                    string jsonData = JsonConvert.SerializeObject(sendData);
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = await client.PostAsync(url, content);
                    response.EnsureSuccessStatusCode();

                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (FileNotFoundException e)
            {
                Console.WriteLine($"Private key file not found: {e.Message}");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"HTTP request error: {e.Message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unexpected error: {e.Message}");
            }
        }
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Success theme={"system"}
  {
      "status": "success",
      "title": "User Profile Title",
      "token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlLZXkiOiJBSjNQR1cxLThIWk04UjQtR0NXVFZKVy1ZRTE1M1BFIiwicHJvZmlsZUtleSI6IjhKNDY4UFktSjM5TVlXRC1IWEpLVlIyLVBRMjBQUlMiLCJpYXQiOjE2MTQyMjYwNDksImV4cCI6MTYxNDIyNjM0OSwiYXVkIjoiaHR0cHM6Ly9hcHAuYXlyc2hhcmUuY29tIiwiaXNzIjoiYm9uZGJyYW5kbG95YWx0eS5jb20iLCJzdWIiOiJzdXBwb3J0QGF5cnNoYXJlLmNvbSJ9.Se387OyhJIdaDkFkvAe0Dwo3pQrHBwdg2bbjqKYn7BZuVDxPboJmTsd7rra8N-Z6b9_fJOtwlRFGBLW1CvgLGU4RSisTVqjqhAkb3KNhpA7cZ673IJbRX-ST7tYadKKzmd9GNrZW9rhxHOlgMJ9uOboc4dcaDbNmzb_yCrfLY-E"
      "url": "https://profile.ayrshare.com?domain=PROVIDED_DOMAIN&jwt=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlLZXkiOiJBSjNQR1cxLThIWk04UjQtR0NXVFZKVy1ZRTE1M1BFIiwicHJvZmlsZUtleSI6IjhKNDY4UFktSjM5TVlXRC1IWEpLVlIyLVBRMjBQUlMiLCJpYXQiOjE2MTQyMjYwNDksImV4cCI6MTYxNDIyNjM0OSwiYXVkIjoiaHR0cHM6Ly9hcHAuYXlyc2hhcmUuY29tIiwiaXNzIjoiYm9uZGJyYW5kbG95YWx0eS5jb20iLCJzdWIiOiJzdXBwb3J0QGF5cnNoYXJlLmNvbSJ9.Se387OyhJIdaDkFkvAe0Dwo3pQrHBwdg2bbjqKYn7BZuVDxPboJmTsd7rra8N-Z6b9_fJOtwlRFGBLW1CvgLGU4RSisTVqjqhAkb3KNhpA7cZ673IJbRX-ST7tYadKKzmd9GNrZW9rhxHOlgMJ9uOboc4dcaDbNmzb_yCrfLY-E",
      "emailSent": true,    
      "expiresIn": "30m"    
  }
  ```

  ```json 400: Private Key Formatted Incorrectly theme={"system"}
  {
    "action": "JWT",
    "status": "error",
    "code": 189,
    "message": "Error generating JWT. Check the sent parameters, such as the privateKey has no extra tabs, spaces, or newlines. Error: error:0909006C:PEM routines:get_name:no start line"
  }
  ```

  ```json 400: Partial Twitter API Keys theme={"system"}
  {
    "action": "JWT",
    "status": "error",
    "code": 188,
    "message": "Both twitterApiKey and twitterApiSecret are required. You provided only one."
  }
  ```

  ```json 400: Duplicate X/Twitter Credentials theme={"system"}
  {
      "action": "JWT",
      "status": "error",
      "code": 434,
      "message": "X/Twitter API credentials were provided in both the request headers and the request body. Please use the headers only. See https://www.ayrshare.com/docs/apis/profiles/generate-jwt"
  }
  ```
</ResponseExample>
