Skip navigation

JWT Authentication for Stream Chat

JWT authentication lets you automatically authorize users in the stream chat and decide on your server who can post in the chat. This is especially useful if you want to integrate the chat with your user management system.

Who this article is for

  • Platform developers — need to integrate stream chat with an authentication system
  • System administrators — need to restrict who can post in stream chat
  • Backend developers — need to set up secure user authorization

When you need JWT chat authentication

Use JWT authentication if:

  • Access control is needed — you want to decide on your server who can write in chat
  • Integration with your system — you need to link chat users with your authentication system
  • Automatic authorization — users should be authorized without additional steps
  • Account system binding — you need to track which of your users is writing in chat
  • Assigning moderators — you want to grant chat moderator rights to users from your system

How JWT works in chat (5 steps)

JWT authentication uses asymmetric cryptography (RSA) for secure transmission of user data:

  1. You create a key pair (private and public) on your server
  2. The public key is saved in Kinescope via API (the private key stays only with you)
  3. Your server creates a JWT token with user data and signs it with the private key
  4. The token is passed in the chat URL as a token parameter
  5. Kinescope verifies the signature with the public key and authorizes the user
Advantage of the asymmetric scheme: The private key never leaves your server. Kinescope only receives the public key and can verify signatures, but cannot create fake tokens. This is more secure than a symmetric scheme (HS256), where a shared secret would need to be transmitted to Kinescope.

How to enable JWT authentication

Authentication is configured individually for each stream via the Kinescope API. Pass the chat_jwt_required: true parameter to enable it:

Important: The API token in the Authorization: Bearer header must be in UUID format. You can get a token from the Kinescope Dashboard in Settings → API tokens. See more about authorization in the general API guidelines.

curl --location --request PUT 'https://api.kinescope.io/v2/live/events/{{event_id}}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_api_token_here' \
--data '{
	"chat_jwt_required": true
}'

After enabling, users will be automatically authorized when following a link with a token:

https://kinescope.io/chat/{{event_id}}?token={{jwt}}
chat_jwt_required only restricts posting. Without a token, a user cannot join the chat, post messages, or ask questions: an attempt to join with just a name fails with access denied. Reading the chat requires no authorization. Anyone who opens https://kinescope.io/chat/{event_id} sees the message feed, the pinned message, thread replies, questions, and the participant list. The participant list shows the names from the username field of users who joined the chat with a token.

Now let’s go through how to set everything up from scratch.

Setup: step 1 — generating keys

JWT authentication uses asymmetric RSA cryptography, which requires a key pair:

  • Private key — stays on your server, used to sign JWT tokens
  • Public key — transmitted to Kinescope via API, used to verify token signatures

What is JWK?

JWK (JSON Web Key) is a standardized format for representing cryptographic keys (RFC 7517). It allows secure key exchange between systems:

  1. Security — the private key never leaves your server
  2. Key rotation — easily replace keys by uploading a new public key
  3. Access revocation — if a key is compromised, immediately delete the public key from Kinescope
  4. Standardization — JWK is supported by most libraries and systems
Why not a symmetric key (HS256)? With a symmetric scheme, you would need to transmit the secret key to Kinescope. This creates a compromise risk: if the key is compromised at Kinescope, an attacker could create fake tokens. With an asymmetric scheme (RS256), even if the public key is compromised, an attacker cannot create tokens since the private key, which stays only with you, is needed for that.

JWK generation example

Here’s what key pair generation looks like:

package main

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/x509"
    "encoding/base64"
    "encoding/json"
    "time"
    
    "github.com/go-jose/go-jose/v3"
)

type JWK struct {
    Kty string `json:"kty"` // key type (RSA)
    Kid string `json:"kid"` // key identifier (unique)
    Use string `json:"use"` // purpose (sig for signing)
    Alg string `json:"alg"` // algorithm (RS256)
    N   string `json:"n"`   // RSA key modulus (base64url-encoded)
    E   string `json:"e"`   // exponent (usually "AQAB")
}

// Generate 2048-bit RSA key pair
func generateRSAKeyPair() (*rsa.PrivateKey, *JWK, error) {
    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        return nil, nil, err
    }
    
    // Generate unique Key ID (kid)
    kid := "key-" + time.Now().Format("2006-01-02")
    
    // Build public key in JWK format
    publicKeyJWK := &JWK{
        Kty: "RSA",
        Kid: kid,
        Use: "sig",   // purpose - signing
        Alg: "RS256", // algorithm - RSA with SHA-256
        N:   base64.RawURLEncoding.EncodeToString(privateKey.PublicKey.N.Bytes()),
        E:   base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}), // 65537 = AQAB
    }
    
    return privateKey, publicKeyJWK, nil
}

// Save private key in PEM format
func savePrivateKey(key *rsa.PrivateKey) ([]byte, error) {
    return x509.MarshalPKCS8PrivateKey(key)
}

Example of a ready public JWK in JSON:

{
  "kty": "RSA",
  "kid": "key-2024-12-25",
  "use": "sig",
  "alg": "RS256",
  "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbwE...",
  "e": "AQAB"
}

Field descriptions:

  • kty — key type (RSA)
  • kid — key identifier (unique in your system)
  • use — key purpose (sig for signing)
  • alg — signing algorithm (RS256 for RSA with SHA-256)
  • n — RSA key modulus (base64url-encoded)
  • e — RSA key exponent (usually AQAB, which means 65537)

Saving the public key in Kinescope

After generating the JWK, save the public part of the key in Kinescope via API. Make sure to pass all parameters: kty, e, use, kid, alg, n, and expires_at (key expiry date in ISO 8601 format):

curl --location 'https://api.kinescope.io/v1/jwk' \
--request POST \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_api_token_here' \
--data '{
	"kty": "RSA",
	"e": "AQAB",
	"use": "sig",
	"kid": "key-2024-12-25",
	"alg": "RS256",
	"n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbwE...",
	"expires_at": "2026-12-31T23:59:59Z"
}'

Example successful response:

{
  "data": {
    "jwk_id": "912ab565-f238-4d71-a4e0-bc93ef70af27",
    "workspace_id": "c3a1b2d4-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
    "kty": "RSA",
    "kid": "key-2024-12-25",
    "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbwE...",
    "e": "AQAB",
    "use": "sig",
    "alg": "RS256",
    "expires_at": "2026-12-31T23:59:59Z"
  }
}

Use the jwk_id value from the response in requests to get or delete the key.

Key management

View all active keys:

curl --location 'https://api.kinescope.io/v1/jwk' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_api_token_here'

Get data for a specific key:

curl --location 'https://api.kinescope.io/v1/jwk/{{jwk_id}}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_api_token_here'

Delete a key:

curl --location --request DELETE 'https://api.kinescope.io/v1/jwk/{{jwk_id}}' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your_api_token_here'

Setup: step 2 — generating a JWT token

Create a JWT token (JSON Web Token, RFC 7519) with required fields and sign it with your private key.

Required fields

  • aud (audience) — value "chat" (required). Kinescope verifies that the token is intended for chat.
  • user_id — unique user identifier in your system, a string. Used for identification in chat.
  • username — username for display in chat. Will be shown next to messages.
  • event_id — stream ID in UUID format (required). It is the same ID as in the /v2/live/events API and in the chat link https://kinescope.io/chat/{event_id}.

Important: event_id is required for chat embedding — chat can be embedded on a page without JWT authentication, but when using JWT, event_id is required to bind the token to a specific stream.

Roles (roles)

The optional roles field grants the user chat moderator rights. Only the moderator value grants rights; it is case-insensitive, and other values are ignored. If the field is missing, the user joins the chat as a regular viewer.

Pass roles as a string or an array of strings:

  • a string: "roles": "moderator"; separate multiple values with commas;
  • an array: "roles": ["moderator"].

Kinescope cannot parse values of other types, such as a number or an array with non-string items: the token is rejected with the jwt invalid error, and the user cannot join the chat.

A user with the moderator role gets moderator tools in the chat:

  • pause the chat;
  • turn message premoderation, slow mode, and the Participants see only their own messages setting on and off;
  • delete individual messages or all messages from an author;
  • block users;
  • pin messages;
  • convert messages into questions and moderate questions.

Chat restrictions do not apply to moderator messages: they are published without premoderation, slow mode does not apply to them, and links can be posted even when Hide users links in chat is enabled.

How to grant and remove the role. The role is applied every time the user joins the chat with a JWT. To grant or remove moderator rights, issue the user a new token with or without the moderator role. The change takes effect when the user joins the chat with the new token, for example after reloading the page. Once the user joins with a token without the role, moderator rights are also removed in their other open chats with the same user_id.

Moderator rights remain until the user joins with a token without the role. Until then, the user stays a moderator in an open chat. Until the old token’s exp passes, the user can join again with it and get moderator rights. After exp passes, the user can join without a token using the session saved in the browser and still keep moderator rights. See Token lifetime and chat session.

Example: setting the role from your system’s data

Node.js (jsonwebtoken):

const jwt = require('jsonwebtoken');

const payload = {
  user_id: String(user.id),
  username: user.name,
  event_id: eventId,
  aud: 'chat',
};
if (user.isModerator) {
  payload.roles = 'moderator'; // or ['moderator']
}

const token = jwt.sign(payload, privateKey, {
  algorithm: 'RS256',
  keyid: 'my-key-2024',
  expiresIn: '1h',
});

Python (PyJWT):

from datetime import datetime, timedelta, timezone

import jwt

payload = {
    'user_id': str(user['id']),
    'username': user['name'],
    'event_id': event_id,
    'aud': 'chat',
    'exp': datetime.now(timezone.utc) + timedelta(hours=1),
}
if user.get('is_moderator'):
    payload['roles'] = 'moderator'  # or ['moderator']

token = jwt.encode(payload, private_key, algorithm='RS256', headers={'kid': 'my-key-2024'})

Go (github.com/golang-jwt/jwt/v5):

claims := jwt.MapClaims{
    "user_id":  userID, // a string
    "username": username,
    "event_id": eventID,
    "aud":      "chat",
    "exp":      time.Now().Add(time.Hour).Unix(),
}
if isModerator {
    claims["roles"] = "moderator" // or []string{"moderator"}
}

token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
token.Header["kid"] = kid

signed, err := token.SignedString(privateKey)
The role cannot be forged. roles is passed inside the token signed with your private key. If a user changes the role in the token, the signature no longer matches, and Kinescope rejects the token. Moderator rights apply only to the chat of the stream whose event_id is in the token.
  • exp (expiration) — token expiry time (Unix timestamp). Recommended to set a short lifespan (e.g., 1 hour).
  • nbf (not before) — time before which the token is invalid (Unix timestamp). Useful for tokens that should become active in the future.
  • iat (issued at) — token creation time (Unix timestamp). Helps track token age.

Kinescope checks these fields when a user joins the chat with a token: a token with an expired exp, or with nbf or iat in the future, is rejected. The fields are optional: a token without exp is accepted too. In an open chat, the token is not checked again — see Token lifetime and chat session.

JWT generation example

Here’s what JWT generation and signing looks like:

package main

import (
    "crypto/rsa"
    "time"
    
    "github.com/golang-jwt/jwt/v5"
)

type ChatClaims struct {
    UserID   string `json:"user_id"`
    Username string `json:"username"`
    EventID  string `json:"event_id"`
    jwt.RegisteredClaims
}

// Generate JWT token
func generateJWT(privateKey *rsa.PrivateKey, kid string, userID, username, eventID string) (string, error) {
    now := time.Now()
    
    claims := ChatClaims{
        UserID:   userID,
        Username: username,
        EventID:  eventID,
        RegisteredClaims: jwt.RegisteredClaims{
            Audience:  []string{"chat"}, // must be "chat"
            IssuedAt:  jwt.NewNumericDate(now),
            ExpiresAt: jwt.NewNumericDate(now.Add(1 * time.Hour)), // default 1 hour
        },
    }
    
    token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
    token.Header["kid"] = kid // Key ID
    
    return token.SignedString(privateKey)
}

// Usage example
func main() {
    privateKey, publicKeyJWK, err := generateRSAKeyPair()
    if err != nil {
        panic(err)
    }
    
    kid := publicKeyJWK.Kid
    
    jwtToken, err := generateJWT(
        privateKey,
        kid,
        "user-12345",                           // User ID
        "John Smith",                           // Username
        "3f2b8c1e-5d4a-4e7b-9a6c-1b2d3e4f5a6b", // Stream ID (UUID)
    )
    if err != nil {
        panic(err)
    }
    
    println("JWT token:", jwtToken)
}

For developers: In a real implementation, use libraries for JWT generation:

  • Node.js: node-jsonwebtoken (jwt.sign()), jose (new SignJWT().setProtectedHeader().sign())
  • Browser: Web Crypto API (crypto.subtle.sign())
  • Python: PyJWT (jwt.encode())
  • Go: github.com/golang-jwt/jwt/v5 (jwt.NewWithClaims().SignedString())

JWT token structure

A JWT consists of three parts separated by dots: header.payload.signature

Header:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "key-2024-12-25"
}

Payload:

{
  "aud": "chat",
  "user_id": "user-12345",
  "username": "John Smith",
  "event_id": "3f2b8c1e-5d4a-4e7b-9a6c-1b2d3e4f5a6b",
  "iat": 1703500800,
  "exp": 1703504400
}

Signature: The signature is created by hashing base64(header) + "." + base64(payload) using the private key with the RS256 algorithm.

Using the token

After generating the token, pass it in the chat URL:

https://kinescope.io/chat/3f2b8c1e-5d4a-4e7b-9a6c-1b2d3e4f5a6b?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImtleS0yMDI0LTEyLTI1In0...

Done! Your users can now be automatically authorized in the stream chat via JWT tokens.

Token lifetime and chat session

The chat checks the token once, when it loads. Kinescope checks the signature, exp, nbf, iat, aud, and event_id, and then opens a chat session of its own for the user. From then on, the chat works with this session and does not check the token again.

  • An expired exp does not disconnect an open chat. The user keeps reading and posting.
  • Reloading with the old token. If the chat loads again with the same token after exp has passed, authorization fails and the chat opens read-only. The user sees no error message: the chat simply has no input field.
  • Joining with a saved session. The session is saved in the user’s browser, in localStorage. If the chat is opened without the token parameter — for example, the iframe loads without a token or the chat link is opened directly — the chat restores the session and the user can post again. This works after exp passes, after the key is deleted, and with chat_jwt_required enabled. The session is restored only in the browser where the user joined with a token.
  • The token cannot be replaced in an open chat. There is no API or postMessage command for this. A new token takes effect only when the chat loads again with it.
  • You cannot revoke a session from your system — neither an open one nor one saved in the browser.

Issue the token when you render the page or create the chat iframe. If your frontend recreates the iframe, request a fresh token from your server for the new URL. A short exp limits only joining with a token: it does not limit how long the user stays in an open chat and does not prevent joining with a saved session.

Security

Key rotation

It is recommended to regularly update keys to improve security. The rotation process:

  1. Generate a new key pair (private and public) with a new kid. A key with a kid that has already been uploaded to Kinescope cannot be uploaded again, even if the earlier key was deleted: the API returns the error A key with this kid is already exists
  2. Upload the new public key to Kinescope via API (the old key will remain active)
  3. Start using the new private key to sign new tokens
  4. After the overlap period (when all old tokens expire), delete the old public key from Kinescope
Overlap period: It is recommended to keep the old key active for a period equal to the maximum token lifespan (e.g., if tokens live 24 hours, keep the old key for 24 hours after starting to use the new one).

Actions when a key is compromised

If the private key was compromised (leak, suspected breach):

  1. Immediately delete the public key from Kinescope via API:
    curl --location --request DELETE 'https://api.kinescope.io/v1/jwk/{{jwk_id}}' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: Bearer your_api_token_here'
    
  2. Generate a new key pair and upload the new public key
  3. Sign new tokens with the new key — Kinescope no longer accepts tokens of the deleted key
  4. Check logs for suspicious activity
Deleting the key does not close chats that are already open. After the key is deleted, users cannot join the chat with tokens signed with it: Kinescope returns jwt parse error. But users who are already in the chat keep reading and posting. They can also join again without a token using the session saved in the browser. See Token lifetime and chat session.

Security recommendations

  • Key size: Use keys of at least 2048 bits (recommended for RSA)
  • Token lifespan: Set a short token lifespan (1–24 hours). The lifetime is checked only when the user joins the chat with a token: an open chat keeps working after exp passes
  • Key lifespan: Set expires_at for public keys (e.g., 1–2 years) and plan rotation before expiry
  • Private key storage: Store the private key in a secure vault (e.g., Kubernetes secrets, AWS Secrets Manager, or an encrypted store)
  • Monitoring: Track key usage and suspicious activity
  • Algorithm: Use RS256 (RSA with SHA-256) and specify it both in the key’s alg field and in the token header

Limitations

  • Signing algorithm: the algorithm in the token header must match the alg field of the uploaded key. For example, an RS384 token with a key that has "alg": "RS256" is rejected with jwt parse error
  • Maximum number of active keys: A limit may apply at the account level (check with support)

Troubleshooting

Token not accepted by the system

Problem: The user cannot authorize, the token is rejected.

Kinescope does not include the rejection reason in the response. The error text only tells you at which stage the token failed verification:

ErrorHTTPCodeWhat failed verification
jwt parse error400400562The token could not be parsed or its signature could not be verified: invalid token format, no kid in the header, the key with this kid is not uploaded, deleted, or expired, the signature does not match the public key
jwt invalid403400561The signature is valid, but the fields failed: exp has expired, the nbf time has not come yet, iat is in the future, aud is not chat, user_id, username, or event_id is missing or not a string, event_id is not a UUID or belongs to another stream, roles is neither a string nor an array of strings

The exact reason is visible only in Kinescope logs. If you cannot find it using the list below, contact technical support and provide the stream ID and a sample token.

Possible causes and solutions:

  1. Invalid token signature

    • Make sure you are using the correct private key for signing
    • Verify that the public key is uploaded to Kinescope and is active
    • Make sure the algorithm in the token header matches the alg field of the uploaded key
  2. Expired key

    • Check the expires_at field of the public key in Kinescope. An expired key is not shown in the key list, and GET /v1/jwk/{{jwk_id}} returns 404 for it
    • If the key has expired, upload a new public key with a new kid
  3. Incorrect event_id

    • Make sure the event_id in the token matches the stream ID and is in UUID format
    • Verify that the stream exists and JWT authentication is enabled for it
    • Important: event_id is required for chat embedding — chat can be embedded without JWT, but when using JWT, a valid event_id is required
  4. Expired token

    • Check the exp field in the token (expiry time)
    • Make sure the system clock on the server is synchronized (NTP)
    • Generate new tokens with an up-to-date expiry time
  5. Incorrect aud field

    • Make sure the aud field has the value "chat" (strictly lowercase)

Moderator role not applied

Problem: The user has no moderator rights even though you passed the moderator role, or still has them after you removed the role.

Possible causes and solutions:

  1. The user has not joined the chat with the new token yet

    • The role is applied when the user joins the chat. A new token takes effect when the user opens the chat with it, for example after reloading the page
    • If you removed the role but the rights remain, the user has not joined with a token without the role yet. Until then, the rights remain in an open chat, when joining with the old token until its exp passes, and when joining without a token using the saved session. See Roles (roles)
  2. The field is not named roles

    • Kinescope reads the role only from the roles field. Fields with other names, such as role, are ignored
  3. The role is misspelled

    • The role must be moderator. For example, moderators does not grant moderator rights

How to verify token validity

You can verify the token locally before sending it to the user. Here is an example verification function:

package main

import (
    "crypto/rsa"
    "errors"
    
    "github.com/golang-jwt/jwt/v5"
)

// Verify JWT token validity
func verifyJWT(tokenString string, publicKey *rsa.PublicKey) (*ChatClaims, error) {
    token, err := jwt.ParseWithClaims(tokenString, &ChatClaims{}, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
            return nil, errors.New("unsupported algorithm")
        }
        return publicKey, nil
    })
    
    if err != nil {
        return nil, err
    }
    
    if claims, ok := token.Claims.(*ChatClaims); ok && token.Valid {
        if !claims.VerifyAudience("chat", true) {
            return nil, errors.New("invalid audience")
        }
        return claims, nil
    }
    
    return nil, errors.New("invalid token")
}

For developers: In a real implementation, use libraries for JWT verification:

  • Node.js: node-jsonwebtoken (jwt.verify()), jose (jwtVerify())
  • Browser: Web Crypto API (crypto.subtle.verify())
  • Python: PyJWT (jwt.decode())
  • Go: github.com/golang-jwt/jwt/v5 (jwt.ParseWithClaims())

Online tools:

  • jwt.io — decoding and checking token structure (without signature verification)
  • Check payload structure: all required fields should be present

Errors when uploading a key

  1. request parameters didn't validate (HTTP 400, code 400400) — a required parameter is missing or the expires_at date has the wrong format. The invalid_params field of the response shows which parameter failed, for example expires_at param is required

    • Pass all parameters: kty, e, n, kid, alg, use, and expires_at
    • Specify the date in ISO 8601 format: "2026-12-31T23:59:59Z"
  2. A key with this kid is already exists (HTTP 400, code 400315) — a key with this kid has already been uploaded to Kinescope, even if it was deleted later

    • Give the new key a new kid
  3. The key was uploaded, but tokens with it are not accepted (jwt parse error) — the key contents are not checked on upload. A key with an error in n or with an expires_at date in the past uploads without an error, but users cannot join the chat with tokens for it. A key with an expires_at date in the past also does not appear in the key list

    • Check that n and e are taken from the public part of your key pair
    • Check that the expires_at date has not passed yet

Chat embed issues

Problem: Chat is not displayed or does not authorize the user when embedded.

Solutions:

  1. Check event_id in the token — it must match the stream ID to which the chat is linked
  2. Make sure JWT authentication is enabled for the stream via API
  3. Check the URL format — the token must be passed as a token parameter:
    https://kinescope.io/chat/{{event_id}}?token={{jwt_token}}
    
    Example:
    https://kinescope.io/chat/3f2b8c1e-5d4a-4e7b-9a6c-1b2d3e4f5a6b?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...
    
  4. Check the browser console for JavaScript errors
  5. The chat opened without an input field and without an error — this is what a rejected token looks like: the chat opens read-only. For example, this happens if the iframe loaded again with an old token whose exp has already passed. Issue a new token and load the chat with it. The error from the table above can be seen in the response to the …/auth request on the Network tab of the browser developer tools

If the problem is not resolved, contact the support chat within the Kinescope interface with:

  • Stream ID (event_id)
  • Token example (sensitive data can be masked)
  • Problem description and reproduction steps

Done! You can now set up JWT authentication for stream chat and automatically authorize users.

What’s next?

  1. Live stream guide — setting up streams in Kinescope
  2. General API guidelines — authorization and request format
  3. Authorization backend — video access control

Still have questions? Write to the support chat within the Kinescope interface — our specialists will help!