# Create Access Tokens for Conversations

This guide covers creating Access Tokens for use with the mobile and web Conversations SDK clients. An Access Token is the credential that your SDK client endpoints must use to identify and authenticate themselves with the default Chat Service instance underneath any Conversation.

If you haven't already, please read our [guide on Conversations SDK client initialization mechanics](/docs/conversations/initializing-conversations-sdk-clients), which introduces the need for a generated Access Token.

Your server or backend generates this Access Token when you authenticate a chat Participant in a Conversation. The Conversations SDK client then uses the token to authorize with the underlying Chat Service.

## Create an Access Token

On your server, you must decide the two following things based on the token request that was sent from the SDK:

* *who the Participant is*
* *what they should be allowed to do*.

To figure out who the chat Participant is (their [identity](/docs/conversations/identity)), you can use your existing login system, session cookies, an API token, or whatever mechanism you use to secure API requests or pages today. Who the chat Participant is and how you authorize their use will vary, depending on your specific application.

Once you determine that the chat Participant should indeed be allowed to access your Conversations application, you can grant that Participant access to Conversations by generating an Access Token as part of your authentication flow. You will then return the token to the user client for use in the Conversations SDK.

When creating an Access Token for Conversation, you will need the following information:

**A Twilio Account SID**

This is the Account SID of your Twilio account and must be the account in which you have created your Conversations Chat Service. (You can [manage your Chat Services in the Twilio Console](/console/chat/services).)

**Chat Service SID**

This SID is the unique identifier for a Chat Service instance, where your Participants, Conversations, Messages and other Conversations-related data reside. This is the Chat Service you grant the SDK client access to.

**Twilio API Key SID**

This is the SID of an API Key created for your Twilio Account, which is used to sign the Access Token cryptographically. You can [create these API keys in the console](/console/chat/dev-tools/api-keys).

**Twilio API Secret**

This is the secret part of the API Key above, also managed in [the Twilio console](/console/chat/dev-tools/api-keys).

**Identity**

The `identity` of your chat Participant. For example, `user@some-domain.com`. For more details around Conversations' use of identity for Chat Participant, please refer to [User Identity & Access Tokens](/docs/chat/identity).

*We recommend following the standard URI specification and avoid the following reserved characters* `! * ' ( ) ; : @ & = + $ , / ? % # [ ]` *for values such as identity and friendly name.*

Creating an Access Token (Chat)

```js
const AccessToken = require('twilio').jwt.AccessToken;
const ChatGrant = AccessToken.ChatGrant;

// Used when generating any kind of tokens
// To set up environmental variables, see http://twil.io/secure
const twilioAccountSid = process.env.TWILIO_ACCOUNT_SID;
const twilioApiKey = process.env.TWILIO_API_KEY;
const twilioApiSecret = process.env.TWILIO_API_SECRET;

// Used specifically for creating Chat tokens
const serviceSid = process.env.TWILIO_CHAT_SERVICE_SID;
const identity = 'user@example.com';

// Create a "grant" which enables a client to use Chat as a given user,
// on a given device
const chatGrant = new ChatGrant({
  serviceSid: serviceSid,
});

// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(
  twilioAccountSid,
  twilioApiKey,
  twilioApiSecret,
  {identity: identity}
);

token.addGrant(chatGrant);

// Serialize the token to a JWT string
console.log(token.toJwt());
```

```py
import os
from twilio.jwt.access_token import AccessToken
from twilio.jwt.access_token.grants import ChatGrant

# required for all twilio access tokens
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
api_key = os.environ['TWILIO_API_KEY']
api_secret = os.environ['TWILIO_API_KEY_SECRET']

# required for Chat grants
service_sid = 'ISxxxxxxxxxxxx'
identity = 'user@example.com'

# Create access token with credentials
token = AccessToken(account_sid, api_key, api_secret, identity=identity)

# Create an Chat grant and add to token
chat_grant = ChatGrant(service_sid=service_sid)
token.add_grant(chat_grant)

# Return token info as JSON
print(token.to_jwt())
```

```cs
using System;
using System.Collections.Generic;
using Twilio.Jwt.AccessToken;

class Example
{
    static void Main(string[] args)
    {
        // These values are necessary for any access token
        // To set up environmental variables, see http://twil.io/secure
        const string twilioAccountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        const string twilioApiKey = Environment.GetEnvironmentVariable("TWILIO_API_KEY");
        const string twilioApiSecret = Environment.GetEnvironmentVariable("TWILIO_API_SECRET");

        // These are specific to Chat
        const string serviceSid = Environment.GetEnvironmentVariable("TWILIO_SERVICE_SID");
        const string identity = "user@example.com";

        // Create an Chat grant for this token

        var grant = new ChatGrant
        {
          ServiceSid = serviceSid
        };

        var grants = new HashSet<IGrant>
        {
            { grant }
        };

        // Create an Access Token generator
        var token = new Token(
            twilioAccountSid,
            twilioApiKey,
            twilioApiSecret,
            identity,
            grants: grants);

        Console.WriteLine(token.ToJwt());
    }
}
```

```java
import com.twilio.jwt.accesstoken.AccessToken;
import com.twilio.jwt.accesstoken.ChatGrant;

public class Example {
  public static void main(String[] args) {
    // Get your Account SID from https://twilio.com/console
    // To set up environment variables, see http://twil.io/secure
    // Required for all types of tokens
    String twilioAccountSid = System.getenv("TWILIO_ACCOUNT_SID");
    String twilioApiKey = System.getenv("TWILIO_API_KEY");
    String twilioApiSecret = System.getenv("TWILIO_API_SECRET");

    String serviceSid = System.getenv("TWILIO_SERVICE_SID");
    String identity = "user@example.com";

    ChatGrant grant = new ChatGrant();
    grant.setServiceSid(serviceSid);

    AccessToken token = new AccessToken.Builder(twilioAccountSid, twilioApiKey, twilioApiSecret)
        .identity(identity).grant(grant).build();

    System.out.println(token.toJwt());
  }
}
```

```go
package main

import (
	"fmt"
	"os"

	"github.com/twilio/twilio-go/client/jwt"
)

func main() {
	// Get your Account SID from https://twilio.com/console
	// To set up environment variables, see http://twil.io/secure
	// Required for all types of tokens
	var twilioAccountSid string = os.Getenv("TWILIO_ACCOUNT_SID")
	var twilioApiKey string = os.Getenv("TWILIO_API_KEY")
	var twilioApiSecret string = os.Getenv("TWILIO_API_SECRET")

	params := jwt.AccessTokenParams{
		AccountSid:    twilioAccountSid,
		SigningKeySid: twilioApiKey,
		Secret:        twilioApiSecret,
		Identity:      "user@example.com",
	}

	jwtToken := jwt.CreateAccessToken(params)
	chatGrant := &jwt.ChatGrant{
		ServiceSid: "ISxxxxxxxxxxxx",
	}

	jwtToken.AddGrant(chatGrant)
	token, err := jwtToken.ToJwt()

	if err != nil {
		error := fmt.Errorf("error: %q", err)
		fmt.Println(error.Error())
	}

	fmt.Println(token)
}
```

```php
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;

// Required for all Twilio access tokens
// To set up environmental variables, see http://twil.io/secure
$twilioAccountSid = getenv('TWILIO_ACCOUNT_SID');
$twilioApiKey = getenv('TWILIO_API_KEY');
$twilioApiSecret = getenv('TWILIO_API_KEY_SECRET');

// Required for Chat grant
$serviceSid = 'ISxxxxxxxxxxxx';
// choose a random username for the connecting user
$identity = "john_doe";

// Create access token, which we will serialize and send to the client
$token = new AccessToken(
    $twilioAccountSid,
    $twilioApiKey,
    $twilioApiSecret,
    3600,
    $identity
);

// Create Chat grant
$chatGrant = new ChatGrant();
$chatGrant->setServiceSid($serviceSid);

// Add grant to token
$token->addGrant($chatGrant);

// render token to string
echo $token->toJWT();
```

```rb
require 'twilio-ruby'

# Required for any Twilio Access Token
# To set up environmental variables, see http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
api_key = ENV['TWILIO_API_KEY']
api_secret = ENV['TWILIO_API_KEY_SECRET']

# Required for Chat
service_sid = 'ISxxxxxxxxxxxx'
identity = 'user@example.com'

# Create Chat grant for our token
grant = Twilio::JWT::AccessToken::ChatGrant.new
grant.service_sid = service_sid

# Create an Access Token
token = Twilio::JWT::AccessToken.new(
  account_sid,
  api_key,
  api_secret,
  [grant],
  identity: identity
)

# Generate the token
puts token.to_jwt
```

**Optional: TTL (Time To Live)**

Access Tokens are only valid for a period of time, given in seconds. The default is `3600` seconds (1 hour), but we recommend adjusting it to several hours. The maximum TTL for a token is 24 hours.

Once your client receives an Access Token from your server, you can initialize the Twilio Conversations SDK and start sending and receiving messages, as covered in our guide to [Initializing SDK Clients](/docs/conversations/initializing-conversations-sdk-clients).
