Skip to content

Commit 8c5fdc3

Browse files
committed
examples: update auth examples to use authCallback instead of authUrl
- auth-generate-jwt: Switch JavaScript and React clients to authCallback - auth-request-token: Switch JavaScript and React clients to authCallback - Fix ES module compatibility (__dirname) in both servers - Change dotenv to load .env instead of .env.local - Fix JWT response format (send as text, not JSON)
1 parent b0edd29 commit 8c5fdc3

7 files changed

Lines changed: 42 additions & 21 deletions

File tree

examples/auth-generate-jwt/javascript/src/script.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,15 @@ function handleConnect() {
1515
messageOne.textContent = '✓';
1616

1717
const realtimeClient = new Ably.Realtime({
18-
authUrl: config.AUTH_URL || 'http://localhost:3001/generate-jwt',
18+
authCallback: async (_tokenParams, callback) => {
19+
try {
20+
const response = await fetch(config.AUTH_URL || 'http://localhost:3001/generate-jwt');
21+
const token = await response.text();
22+
callback(null, token);
23+
} catch (error) {
24+
callback(error instanceof Error ? error.message : String(error), null);
25+
}
26+
},
1927
});
2028

2129
const messageTwo = document.getElementById('message-2');

examples/auth-generate-jwt/react/src/App.tsx

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState, useEffect } from 'react';
1+
import React, { useState } from 'react';
22
import * as Ably from 'ably';
33
import { AblyProvider, useConnectionStateListener } from 'ably/react';
44
import './styles/styles.css';
@@ -59,7 +59,15 @@ export default function App() {
5959

6060
// Initialize Ably client with JWT auth
6161
const realtimeClient = new Ably.Realtime({
62-
authUrl: config.AUTH_URL || 'http://localhost:3001/generate-jwt',
62+
authCallback: async (_tokenParams, callback) => {
63+
try {
64+
const response = await fetch(config.AUTH_URL || 'http://localhost:3001/generate-jwt');
65+
const token = await response.text();
66+
callback(null, token);
67+
} catch (error) {
68+
callback(error instanceof Error ? error.message : String(error), null);
69+
}
70+
},
6371
});
6472

6573
// Update second message

examples/auth-generate-jwt/server/src/server.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import express from 'express';
22
import path from 'path';
3+
import { fileURLToPath } from 'url';
34
import dotenv from 'dotenv';
45
import cors from 'cors';
56
import crypto from 'crypto';
67

8+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
79
dotenv.config({ path: path.resolve(__dirname, '../../../.env.local') });
810

911
const app = express();
@@ -21,8 +23,6 @@ function base64urlEncode(str: string) {
2123
}
2224

2325
app.get('/generate-jwt', async (_req, res) => {
24-
console.log('1 - /generate-jwt endpoint called');
25-
2626
const ablyApiKey = process.env.VITE_ABLY_KEY || '';
2727
const [apiKeyName, apiKeySecret] = ablyApiKey.split(':');
2828
try {
@@ -51,8 +51,7 @@ app.get('/generate-jwt', async (_req, res) => {
5151
const signature = base64urlEncode(hmac.digest('base64'));
5252
const ablyJwt = base64Header + '.' + base64Claims + '.' + signature;
5353

54-
console.log('2 - JWT generated: ', ablyJwt);
55-
res.json(ablyJwt);
54+
res.type('application/jwt').send(ablyJwt);
5655
} catch (error) {
5756
res.status(500).json({ error: 'Failed to generate token' });
5857
}

examples/auth-request-token/javascript/src/script.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,15 @@ function handleConnect() {
1515
messageOne.textContent = '✓';
1616

1717
const realtimeClient = new Ably.Realtime({
18-
authUrl: config.AUTH_URL || 'http://localhost:3001/request-token',
18+
authCallback: async (_tokenParams, callback) => {
19+
try {
20+
const response = await fetch(config.AUTH_URL || 'http://localhost:3001/request-token');
21+
const token = await response.text();
22+
callback(null, token);
23+
} catch (error) {
24+
callback(error instanceof Error ? error.message : String(error), null);
25+
}
26+
},
1927
});
2028

2129
const messageTwo = document.getElementById('message-2');

examples/auth-request-token/react/src/App.tsx

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,15 @@ export default function App() {
5959

6060
// Initialize Ably client with token auth
6161
const realtimeClient = new Ably.Realtime({
62-
authUrl: config.AUTH_URL || 'http://localhost:3001/request-token',
62+
authCallback: async (_tokenParams, callback) => {
63+
try {
64+
const response = await fetch(config.AUTH_URL || 'http://localhost:3001/request-token');
65+
const token = await response.text();
66+
callback(null, token);
67+
} catch (error) {
68+
callback(error instanceof Error ? error.message : String(error), null);
69+
}
70+
},
6371
});
6472

6573
// Update second message

examples/auth-request-token/server/src/server.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import express from 'express';
22
import path from 'path';
3+
import { fileURLToPath } from 'url';
34
import dotenv from 'dotenv';
45
import cors from 'cors';
56
import Ably from 'ably';
67

8+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
79
dotenv.config({ path: path.resolve(__dirname, '../../../.env.local') });
810

911
const app = express();
@@ -19,10 +21,8 @@ app.use(
1921
const ably = new Ably.Rest(process.env.VITE_ABLY_KEY || '');
2022

2123
app.get('/request-token', async (_req, res) => {
22-
console.log('1 - /request-token endpoint called');
2324
try {
2425
const tokenRequest = await ably.auth.requestToken({ clientId: 'example-client-id' });
25-
console.log('2 - Token generated:', tokenRequest);
2626
res.json(tokenRequest);
2727
} catch (error) {
2828
res.status(500).json({ error: 'Failed to generate token' });

src/data/examples/index.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,6 @@ export const examples: Example[] = [
4343
metaTitle: `Authenticate with Ably Token`,
4444
metaDescription: `Learn how to request and use Ably Tokens for client authentication. Secure token-based auth for realtime applications.`,
4545
},
46-
{
47-
id: 'auth-request-token',
48-
name: 'Request Token',
49-
description: 'Request an Ably Token for authenticating users.',
50-
products: ['auth'],
51-
layout: 'single-horizontal',
52-
visibleFiles: ['src/script.ts', 'App.tsx', 'Chat.tsx', 'Home.tsx', 'index.tsx'],
53-
metaTitle: `Authenticate with Ably Token`,
54-
metaDescription: `Learn how to request and use Ably Tokens for client authentication. Secure token-based auth for realtime applications.`,
55-
},
5646
{
5747
id: 'chat-presence',
5848
name: 'Chat presence',

0 commit comments

Comments
 (0)