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

# Authenticate with a temporary token

export const EndpointCard = ({method = "API", title, children, href, arrow = true}) => {
  const METHOD_STYLES = {
    GET: {
      bg: "mint-bg-green-400/20 dark:mint-bg-green-400/20",
      text: "mint-text-green-700 dark:mint-text-green-400",
      border: "mint-border-green-300 dark:mint-border-green-700"
    },
    POST: {
      bg: "mint-bg-blue-400/20 dark:mint-bg-blue-400/20",
      text: "mint-text-blue-700 dark:mint-text-blue-400"
    },
    PUT: {
      bg: "mint-bg-yellow-400/20 dark:mint-bg-yellow-400/20",
      text: "mint-text-yellow-700 dark:mint-text-yellow-400"
    },
    PATCH: {
      bg: "mint-bg-orange-400/20 dark:mint-bg-orange-400/20",
      text: "mint-text-orange-700 dark:mint-text-orange-400"
    },
    DELETE: {
      bg: "mint-bg-red-400/20 dark:mint-bg-red-400/20",
      text: "mint-text-red-700 dark:mint-text-red-400"
    },
    API: {
      bg: "mint-bg-black",
      text: "mint-text-white"
    }
  };
  const MethodBadge = ({method}) => {
    const style = METHOD_STYLES[method?.toUpperCase()] ?? METHOD_STYLES.GET;
    return <span className={`
          method-pill rounded-lg font-semibold px-1.5 py-0.5 text-xs leading-5 ${style.bg} ${style.text}`}>
        {method?.toUpperCase()}
      </span>;
  };
  const content = <div className="flex items-center gap-4 bg-white dark:bg-background-dark border border-gray-200 dark:border-gray-700 rounded-xl p-5 hover:border-gray-400 dark:hover:border-gray-500 hover:shadow-md transition-all cursor-pointer card block font-normal group relative my-2 ring-2 ring-transparent rounded-2xl bg-white dark:bg-background-dark border border-gray-950/10 dark:border-white/10 overflow-hidden w-full cursor-pointer hover:!border-primary dark:hover:!border-primary-light">
      {}
      <div className="shrink-0">
        <MethodBadge method={method} />
      </div>
      {}
      <div className="flex-1 min-w-0">
        <p className="font-semibold text-gray-900 dark:text-white text-base leading-snug">{title}</p>
        {children && <p className="mt-1 text-sm text-gray-500 dark:text-gray-400 line-clamp-2">{children}</p>}
      </div>
    </div>;
  if (!href) return content;
  return <a href={href} className="block no-underline border-b-0 mb-2">
      {content}
    </a>;
};

## Authenticate with a temporary token

If you need to authenticate on the client, you can avoid exposing your API key by using temporary authentication tokens.
You should generate this token on your server and pass it to the client.

<EndpointCard title="Generate streaming token" href="/api-reference/streaming-api/generate-streaming-token" method="GET">
  View the endpoint reference.
</EndpointCard>

<Steps>
  <Step>
    <Tabs groupId="language">
      <Tab language="python" title="Python" default>
        To generate a temporary token, make a `POST` request to the temporary [token endpoint](/api-reference/streaming-api/generate-streaming-token).

        Use the `expires_in_seconds` parameter to specify the duration for which the token will remain valid. Optionally, use the `max_session_duration_seconds` parameter to specify the desired maximum duration for the session initialized using this token.

        ```python theme={null}
        import requests
        from urllib.parse import urlencode


        def create_temporary_token():
            url = "https://streaming.assemblyai.com/v3/token"
            response = requests.get(
                f"{url}?{urlencode({'expires_in_seconds': 60})}",
                headers={"Authorization": "<YOUR_API_KEY>"},
            )
            data = response.json()
            return data.get("token")
        ```
      </Tab>

      <Tab language="python-sdk" title="Python SDK">
        To generate a temporary token, call `StreamingClient.create_temporary_token()`.

        Use the `expires_in_seconds` parameter to specify the duration for which the token will remain valid. Optionally, use the `max_session_duration_seconds` parameter to specify the desired maximum duration for the session started using this token.

        ```python theme={null}
        from assemblyai.streaming.v3 import StreamingClient, StreamingClientOptions


        def create_temporary_token():
            client = StreamingClient(
                StreamingClientOptions(
                    api_key="<YOUR_API_KEY>",
                    api_host="streaming.assemblyai.com",
                )
            )

            return client.create_temporary_token(expires_in_seconds=60)
        ```
      </Tab>

      <Tab language="javascript" title="JavaScript">
        To generate a temporary token, make a `POST` request to the temporary [token endpoint](/api-reference/streaming-api/generate-streaming-token).

        Use the `expires_in_seconds` parameter to specify the duration for which the token will remain valid. Optionally, use the `max_session_duration_seconds` parameter to specify the desired maximum duration for the session started using this token.

        ```js theme={null}
        async function createTemporaryToken() {
          const url = new URL("https://streaming.assemblyai.com/v3/token");
          url.search = new URLSearchParams({
            expires_in_seconds: 60,
          }).toString();

          const response = await fetch(url, {
            headers: {
              Authorization: "<YOUR_API_KEY>",
            },
          });

          const data = await response.json();
          return data.token;
        }
        ```
      </Tab>

      <Tab language="javascript-sdk" title="JavaScript SDK">
        To generate a temporary token, call `client.streaming.createTemporaryToken()`.

        Use the `expires_in_seconds` parameter to specify the duration for which the token will remain valid. Optionally, use the `max_session_duration_seconds` parameter to specify the desired maximum duration for the session started using this token.

        ```js theme={null}
        import { AssemblyAI } from "assemblyai";

        async function createTemporaryToken() {
          const client = new AssemblyAI({ apiKey: "<YOUR_API_KEY>" });
          return client.streaming.createTemporaryToken({
            expires_in_seconds: 60,
          });
        }
        ```
      </Tab>
    </Tabs>

    <Note>
      `expires_in_seconds` must be a value between `1` and `600` seconds. If
      specified, `max_session_duration_seconds` must be a value between `60` and
      `10800` seconds (defaults to maximum session duration of 3 hours).
    </Note>
  </Step>

  <Step>
    The client should retrieve the token from the server and use the token to authenticate the transcriber.

    <Note>
      Each token has a one-time use restriction and can only be used for a single
      session. Any usage associated with a temporary token will be attributed to the
      API key that generated it.
    </Note>

    <Tabs groupId="language">
      <Tab language="python" title="Python" default>
        To use it, specify the `token` parameter as a query parameter in the WebSocket URL.

        ```python theme={null}
        params_w_token = {**CONNECTION_PARAMS, "speech_model": "universal-3-5-pro", "token": token}
        ws_app = websocket.WebSocketApp(
            f'{API_ENDPOINT_BASE_URL}?{urlencode(params_w_token)}',
            on_open=on_open,
            on_message=on_message,
            on_error=on_error,
            on_close=on_close,
        )
        ```
      </Tab>

      <Tab language="python-sdk" title="Python SDK">
        To use it, specify the `token` parameter when initializing the `StreamingClient`.

        ```python theme={null}
        client = StreamingClient(
            StreamingClientOptions(
                token=token,
                api_host="streaming.assemblyai.com",
            )
        )

        client.connect(
            StreamingParameters(
                sample_rate=16000,
                speech_model="universal-3-5-pro",
            )
        )
        ```
      </Tab>

      <Tab language="javascript" title="JavaScript">
        To use it, specify the `token` parameter as a query parameter in the WebSocket URL.

        ```js theme={null}
        const token = await getToken(); // Implement getToken to retrieve token from server
        const paramsWithToken = { ...CONNECTION_PARAMS, speech_model: "universal-3-5-pro", token };
        ws = new WebSocket(
          `${API_ENDPOINT_BASE_URL}?${querystring.stringify(paramsWithToken)}`
        );
        ```
      </Tab>

      <Tab language="javascript-sdk" title="JavaScript SDK">
        To use it, specify the `token` parameter when initializing the `StreamingTranscriber`.

        ```js theme={null}
        import { StreamingTranscriber } from "assemblyai";

        const token = await getToken(); // Implement getToken to retrieve token from server
        const rt = new StreamingTranscriber({
          token,
          sampleRate: 16_000,
          speechModel: "universal-3-5-pro",
        });
        ```
      </Tab>
    </Tabs>
  </Step>
</Steps>
