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

# Authentication

The Authentication API manages authentication and authorization for Realtime SDK connections. Use the `auth` object to request tokens, authorize connections, and manage client identity.

## Auth Object

Access the `auth` object from your Realtime client instance:

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime('your-api-key');
  const auth = realtime.auth;
  ```

  ```python theme={null}
  realtime = AblyRealtime('your-api-key')
  auth = realtime.auth
  ```
</Code>

## Properties

<ParamField path="clientId" type="string">
  The client ID string configured for this connection. Returns `null` if no client ID is set.

  See [identified clients](/docs/auth/identified-clients) for more information.
</ParamField>

## Methods

### authorize

`authorize(tokenParams?, authOptions?): Promise<TokenDetails>`

Obtain a new token and upgrade the current connection to use it. This method also updates the default `tokenParams` and `authOptions` for future token requests.

<Code>
  ```javascript theme={null}
  try {
    const tokenDetails = await realtime.auth.authorize({
      clientId: 'user-123',
      ttl: 3600000
    });
    console.log('Authorized with token:', tokenDetails.token);
  } catch (error) {
    console.error('Authorization failed:', error);
  }
  ```

  ```python theme={null}
  try:
      token_details = await realtime.auth.authorize(
          token_params={'clientId': 'user-123', 'ttl': 3600000}
      )
      print('Authorized with token:', token_details.token)
  except AblyException as error:
      print('Authorization failed:', error)
  ```
</Code>

<ParamField body="tokenParams" type="object">
  Optional token parameters to use for the token request:

  * `ttl` (integer): Token time-to-live in milliseconds (default: 60 minutes)
  * `capability` (string): JSON-encoded capability specification
  * `clientId` (string): Client ID to associate with the token
  * `timestamp` (integer): Timestamp for the token request
</ParamField>

<ParamField body="authOptions" type="object">
  Optional authentication options:

  * `authUrl` (string): URL to request token from
  * `authCallback` (function): Callback function to obtain token
  * `authMethod` (string): HTTP method for authUrl (`GET` or `POST`)
  * `authHeaders` (object): HTTP headers for authUrl request
  * `authParams` (object): Query parameters for authUrl request
</ParamField>

#### Returns

Returns a Promise that resolves with a `TokenDetails` object containing:

* `token` (string): The token string
* `expires` (integer): Expiry time in milliseconds since epoch
* `issued` (integer): Issue time in milliseconds since epoch
* `capability` (string): JSON-encoded capability
* `clientId` (string): Client ID associated with token

### createTokenRequest

`createTokenRequest(tokenParams?, authOptions?): Promise<TokenRequest>`

Create and sign an Ably TokenRequest for use by other clients. This requires an API key to be configured locally.

<Code>
  ```javascript theme={null}
  try {
    const tokenRequest = await realtime.auth.createTokenRequest({
      clientId: 'user-123',
      capability: '{"channel1":["subscribe"]}'
    });
    
    // Send tokenRequest to client
    sendToClient(tokenRequest);
  } catch (error) {
    console.error('Failed to create token request:', error);
  }
  ```

  ```python theme={null}
  try:
      token_request = await realtime.auth.create_token_request(
          token_params={
              'clientId': 'user-123',
              'capability': '{"channel1":["subscribe"]}'
          }
      )
      # Send token_request to client
      send_to_client(token_request)
  except AblyException as error:
      print('Failed to create token request:', error)
  ```
</Code>

<ParamField body="tokenParams" type="object">
  Same as `authorize()` method.
</ParamField>

<ParamField body="authOptions" type="object">
  Same as `authorize()` method.
</ParamField>

#### Returns

Returns a Promise that resolves with a `TokenRequest` object containing:

* `keyName` (string): API key name
* `ttl` (integer): Token time-to-live
* `timestamp` (integer): Request timestamp
* `capability` (string): Capability specification
* `clientId` (string): Client ID
* `nonce` (string): Random nonce
* `mac` (string): HMAC signature

### requestToken

`requestToken(tokenParams?, authOptions?): Promise<TokenDetails>`

Request an Ably Token from the Ably service. This method issues a new token request to Ably and returns the token.

<Code>
  ```javascript theme={null}
  try {
    const tokenDetails = await realtime.auth.requestToken({
      clientId: 'user-123'
    });
    console.log('Token received:', tokenDetails.token);
  } catch (error) {
    console.error('Token request failed:', error);
  }
  ```

  ```python theme={null}
  try:
      token_details = await realtime.auth.request_token(
          token_params={'clientId': 'user-123'}
      )
      print('Token received:', token_details.token)
  except AblyException as error:
      print('Token request failed:', error)
  ```
</Code>

<ParamField body="tokenParams" type="object">
  Same as `authorize()` method.
</ParamField>

<ParamField body="authOptions" type="object">
  Same as `authorize()` method.
</ParamField>

#### Returns

Returns a Promise that resolves with a `TokenDetails` object (same as `authorize()`).

### revokeTokens

`revokeTokens(specifiers): Promise<void>`

Revoke one or more tokens. This is useful for logging out users or revoking compromised tokens.

<Code>
  ```javascript theme={null}
  try {
    await realtime.auth.revokeTokens([
      { type: 'token', value: 'xVLyHw.token-string' }
    ]);
    console.log('Token revoked successfully');
  } catch (error) {
    console.error('Token revocation failed:', error);
  }
  ```

  ```python theme={null}
  try:
      await realtime.auth.revoke_tokens([
          {'type': 'token', 'value': 'xVLyHw.token-string'}
      ])
      print('Token revoked successfully')
  except AblyException as error:
      print('Token revocation failed:', error)
  ```
</Code>

<ParamField body="specifiers" type="array" required>
  Array of token specifier objects:

  * `type` (string): Specifier type (`token` or `clientId`)
  * `value` (string): Token string or client ID to revoke
</ParamField>

## Authentication Strategies

### Basic Authentication

Use your API key directly (server-side only):

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime('your-api-key');
  ```
</Code>

### Token Authentication

Use tokens for enhanced security (client-side):

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime({
    authUrl: 'https://your-server.com/auth'
  });
  ```
</Code>

### Auth Callback

Provide a callback function to obtain tokens:

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime({
    authCallback: async (tokenParams, callback) => {
      try {
        const token = await fetchTokenFromServer();
        callback(null, token);
      } catch (error) {
        callback(error, null);
      }
    }
  });
  ```
</Code>

## Related Resources

* [Authentication Guide](/docs/auth)
* [Token Authentication](/docs/auth/token)
* [Identified Clients](/docs/auth/identified-clients)
* [Capabilities](/docs/auth/capabilities)
