> ## 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.

# Tạo một JWT

> Tạo JSON Web Token (JWT) để sử dụng với single sign on.

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} />

Tạo JSON Web Token (JWT) để sử dụng với single sign on.

Xem [Tổng quan Generate JWT](/apis/profiles/generate-jwt-overview) để biết thêm chi tiết.

<Note>
  URL JWT có hiệu lực trong **5 phút**. Sau 5 phút bạn phải tạo URL JWT mới.
  Xem Max Pack `expiresIn` để biết [các tùy chọn bổ sung](/apis/profiles/generate-jwt-overview#jwt-expires-in).
</Note>

## Tham số Header

<HeaderAPI noProfileKey />

<ParamField header="X-Twitter-OAuth1-Api-Key" type="string">
  X API Key (Consumer Key) của bạn từ X Developer Portal. Thay thế cho tham số body `twitterApiKey`. Khi được cung cấp, URL JWT được tạo sẽ sử dụng X Developer App của bạn cho liên kết OAuth.
</ParamField>

<ParamField header="X-Twitter-OAuth1-Api-Secret" type="string">
  X API Secret (Consumer Secret) của bạn từ X Developer Portal. Thay thế cho tham số body `twitterApiSecret`. Bắt buộc khi `X-Twitter-OAuth1-Api-Key` được cung cấp.
</ParamField>

<Info>
  **Khuyến nghị:** Truyền thông tin xác thực X qua header (`X-Twitter-OAuth1-Api-Key` và `X-Twitter-OAuth1-Api-Secret`) để nhất quán với tất cả các endpoint API Ayrshare khác. Các tham số body `twitterApiKey` và `twitterApiSecret` vẫn được hỗ trợ để tương thích ngược.
</Info>

## Tham số Body

<ParamField body="domain" type="string" required>
  Miền của ứng dụng. Vui lòng sử dụng chính xác miền được cấp trong quá trình onboarding.
</ParamField>

<ParamField body="privateKey" type="string" required>
  Private Key được sử dụng để mã hóa.
</ParamField>

<ParamField body="profileKey" type="string" required>
  User Profile Key. API Key không thể được sử dụng trong trường này.
</ParamField>

<ParamField body="logout" type="boolean" default={false}>
  Tự động đăng xuất phiên hiện tại. Không khuyến nghị sử dụng trong production vì nó ảnh hưởng đến hiệu suất.

  Xem [Tự động đăng xuất phiên Profile](/multiple-users/api-integration-business#automatic-logout-of-a-profile-session) để biết thêm thông tin.
</ParamField>

<ParamField body="redirect" type="string">
  Chỉ định một URL để chuyển hướng đến khi nút "Done" hoặc hình ảnh logo được nhấp. URL sẽ tự động được rút gọn trong URL JWT được trả về. [Chuyển hướng cửa sổ opener gốc](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url) bằng cách thêm tham số truy vấn `origin=true` vào URL chuyển hướng.
</ParamField>

<ParamField body="allowedSocial" type="array">
  Chỉ định các mạng xã hội hiển thị trong trang liên kết. Điều này sẽ ghi đè các mạng xã hội được cấu hình trong trang [Social Networks](/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">
  Ghi đè luồng liên kết Instagram nào được sử dụng khi người dùng nhấp vào nút Instagram trên trang liên kết mạng xã hội cho URL này. Các giá trị hợp lệ:

  * `instagram`: Instagram Login trực tiếp, không yêu cầu Facebook Page.
  * `facebook`: Liên kết Instagram thông qua Facebook Page đã kết nối.

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

  Khi bị bỏ qua, trang liên kết sử dụng cài đặt [Instagram Login](/multiple-users/manage-user-profiles#instagram-login) toàn tài khoản của bạn.

  Xem [Phương thức liên kết Instagram](/apis/profiles/generate-jwt-overview#instagram-link-method) để biết thêm thông tin.
</ParamField>

<ParamField body="verify" type="boolean" default={false}>
  Xác minh rằng token được tạo là hợp lệ. Khuyến nghị chỉ sử dụng trong môi trường không phải production.

  Xem [Mở và đóng URL liên kết mạng xã hội](/multiple-users/api-integration-business#opening-and-closing-the-social-linking-url) để biết thêm thông tin.
</ParamField>

<ParamField body="base64" type="boolean" default={false}>
  Nếu private key được mã hóa base64, đặt thành `true`.

  Mã hóa tệp private.key ở dạng base64 và truyền chuỗi một dòng vào trường `privateKey`.

  Ví dụ trên Linux: `cat private.key | base64`
</ParamField>

<ParamField body="expiresIn" type="number" default={5}>
  Đặt thời hạn của token tính bằng phút. Phạm vi: 1 phút đến 2880 phút.

  Xem [JWT Expires In](/apis/profiles/generate-jwt-overview#jwt-expires-in) để biết thêm thông tin.
</ParamField>

<ParamField body="email" type="object" default={5}>
  Gửi email Connect Accounts với một liên kết để người dùng truy cập trực tiếp vào trang liên kết mạng xã hội của họ.

  Xem [Connect Accounts Email](/apis/profiles/generate-jwt-overview#connect-accounts-email) để biết thêm thông tin.
</ParamField>

<Info>
  Khi bạn bao gồm thông tin xác thực X API của mình, URL JWT được tạo sẽ khởi tạo liên kết OAuth bằng X Developer App của riêng bạn. Người dùng cuối của bạn sẽ thấy tên ứng dụng của bạn trên màn hình đồng ý X.
</Info>

<Warning>
  **Bắt buộc:** Trước khi sử dụng tính năng này, bạn phải thêm các URL callback này vào cài đặt X Developer App của mình (trong Authentication settings > Callback URI / Redirect URL):

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

  Nếu không có các URL này, luồng OAuth sẽ thất bại với lỗi `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>
