Skip to content

Commit 232d878

Browse files
committed
update
1 parent a72aa04 commit 232d878

File tree

6 files changed

+106
-44
lines changed

6 files changed

+106
-44
lines changed

articles/azure-web-pubsub/howto-connect-mqtt-websocket-client.md

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,24 @@ ms.topic: how-to
1010

1111
# How To Connect MQTT Clients to Web PubSub
1212

13-
MQTT is a lightweight pub/sub messaging protocol designed for devices with limited resources.
13+
MQTT is a lightweight pub/sub messaging protocol designed for devices with constrained resources.
1414

1515
In this article, we introduce how to connect MQTT clients to the service, so that the clients can publish and subscribe messages.
1616

1717
## Connection Parameters
1818

19+
WebSocket connection URI: `wss://{serviceName}.webpubsub.azure.com/clients/mqtt/hubs/{hub}?access_token={token}`.
20+
21+
* {hub} is a mandatory parameter that provides isolation for different applications.
22+
* {token} is required by default. Alternatively, you can include the token in the `Authorization` header in the format `Bearer {token}`. You can bypass the token requirement by enabling anonymous access to the hub. <!--TODO MQTT allow anonymous access to the hub-->
23+
24+
If client library doesn't accept a URI, then you probably need to split the information in the URI into multiple parameters:
25+
26+
* Host: `{serviceName}.webpubsub.azure.com`
27+
* Path: `/clients/mqtt/hubs/{hub}?access_token={token}`
28+
* Port: 443
29+
* Transport: WebSockets with [TLS](https://wikipedia.org/wiki/Transport_Layer_Security).
30+
1931
[!INCLUDE [MQTT-Connection-Parameters](includes/mqtt-connection-Parameters.md)]
2032

2133
By default MQTT clients don't have any permissions to publish or subscribe to any topics. You need to grant [permissions](#permissions) to MQTT clients.
@@ -61,9 +73,49 @@ You could also configure properties for the client connection when generating th
6173

6274
You could also add custom claims into the access token, and these values are preserved as the `claims` property in [connect upstream request body](./reference-mqtt-cloud-events.md#system-connect-event).
6375

64-
[Server SDKs](./howto-generate-client-access-url.md#generate-from-service-sdk) provides APIs to generate the access token for the clients.
76+
[Server SDKs](./howto-generate-client-access-url.md#generate-from-service-sdk) provides APIs to generate the access token for MQTT clients. Note that you must specify the client protocol to `Mqtt`.
77+
78+
# [JavaScript](#tab/javascript)
79+
80+
1. Follow [Getting started with server SDK](./reference-server-sdk-js.md#getting-started) to create a `WebPubSubServiceClient` object `service`
81+
82+
2. Generate Client Access URL by calling `WebPubSubServiceClient.getClientAccessToken`:
83+
84+
```js
85+
let token = await serviceClient.getClientAccessToken({ clientProtocol: "mqtt" });
86+
```
87+
88+
# [C#](#tab/csharp)
89+
90+
1. Follow [Getting started with server SDK](./reference-server-sdk-csharp.md#getting-started) to create a `WebPubSubServiceClient` object `service`
91+
92+
2. Generate Client Access URL by calling `WebPubSubServiceClient.GetClientAccessUri`:
93+
94+
```csharp
95+
var url = service.GetClientAccessUri(clientProtocol: WebPubSubClientProtocol.Mqtt);
96+
```
97+
98+
# [Python](#tab/python)
99+
100+
1. Follow [Getting started with server SDK](./reference-server-sdk-python.md#install-the-package) to create a `WebPubSubServiceClient` object `service`
101+
102+
2. Generate Client Access URL by calling `WebPubSubServiceClient.get_client_access_token`:
103+
104+
```python
105+
token = service.get_client_access_token(client_protocol="MQTT")
106+
```
107+
108+
# [Java](#tab/java)
109+
110+
1. Follow [Getting started with server SDK](./reference-server-sdk-java.md#getting-started) to create a `WebPubSubServiceClient` object `service`
111+
112+
2. Generate Client Access URL by calling `WebPubSubServiceClient.getClientAccessToken`:
65113

66-
<!--TODO Give a simple sample for each language here, and also add link to the generation link-->
114+
```java
115+
GetClientAccessTokenOptions option = new GetClientAccessTokenOptions();
116+
option.setWebPubSubClientAccess(WebPubSubClientProtocol.MQTT);
117+
WebPubSubClientAccessToken token = service.getClientAccessToken(option);
118+
```
67119

68120
### 2. Upstream Server Workflow
69121

articles/azure-web-pubsub/howto-generate-client-access-url.md

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ The same Client Access URL can be generated by using the Web PubSub server SDK.
3838

3939
2. Generate Client Access URL by calling `WebPubSubServiceClient.getClientAccessToken`:
4040

41+
- Generate MQTT client access token
42+
43+
```js
44+
let token = await serviceClient.getClientAccessToken({ clientProtocol: "mqtt" });
45+
```
46+
4147
- Configure user ID
4248

4349
```js
@@ -82,6 +88,12 @@ The same Client Access URL can be generated by using the Web PubSub server SDK.
8288

8389
2. Generate Client Access URL by calling `WebPubSubServiceClient.GetClientAccessUri`:
8490

91+
- Generate MQTT client access token
92+
93+
```csharp
94+
var url = service.GetClientAccessUri(clientProtocol: WebPubSubClientProtocol.Mqtt);
95+
```
96+
8597
- Configure user ID
8698

8799
```csharp
@@ -118,6 +130,12 @@ The same Client Access URL can be generated by using the Web PubSub server SDK.
118130

119131
2. Generate Client Access URL by calling `WebPubSubServiceClient.get_client_access_token`:
120132

133+
- Generate MQTT client access token
134+
135+
```python
136+
token = service.get_client_access_token(client_protocol="MQTT")
137+
```
138+
121139
- Configure user ID
122140

123141
```python
@@ -154,7 +172,15 @@ The same Client Access URL can be generated by using the Web PubSub server SDK.
154172

155173
2. Generate Client Access URL by calling `WebPubSubServiceClient.getClientAccessToken`:
156174

157-
- Configure user ID
175+
- Generate MQTT client access token
176+
177+
```java
178+
GetClientAccessTokenOptions option = new GetClientAccessTokenOptions();
179+
option.setWebPubSubClientAccess(WebPubSubClientProtocol.MQTT);
180+
WebPubSubClientAccessToken token = service.getClientAccessToken(option);
181+
```
182+
183+
- Configure user ID
158184

159185
```java
160186
GetClientAccessTokenOptions option = new GetClientAccessTokenOptions();
@@ -209,7 +235,7 @@ You can enable Microsoft Entra ID in your service and use the Microsoft Entra to
209235
> [!NOTE]
210236
> Please use the latest version of Postman. Old versions of Postman have [some issue](https://github.com/postmanlabs/postman-app-support/issues/3994#issuecomment-893453089) supporting colon `:` in path.
211237

212-
1. For the URI, enter `https://{Endpoint}/api/hubs/{hub}/:generateToken?api-version=2024-01-01`. For MQTT clients, append query parameter `&clientType=mqtt` to the URL.
238+
1. For the URI, enter `https://{Endpoint}/api/hubs/{hub}/:generateToken?api-version=2024-01-01`. If you'd like to generate token for MQTT clients, append query parameter `&clientType=mqtt` to the URL.
213239
2. On the **Auth** tab, select **Bearer Token** and paste the Microsoft Entra token fetched in the previous step
214240
3. Select **Send** and you see the Client Access Token in the response:
215241

articles/azure-web-pubsub/includes/mqtt-connection-parameters.md

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,6 @@ ms.topic: include
66
ms.date: 06/22/2024
77
---
88

9-
WebSocket connection URI: `wss://{serviceName}.webpubsub.azure.com/clients/mqtt/hubs/{hub}?access_token={token}`.
10-
11-
* {hub} is a mandatory parameter that provides isolation for different applications.
12-
* {token} is required by default. Alternatively, you can include the token in the `Authorization` header in the format `Bearer {token}`. You can bypass the token requirement by enabling anonymous access to the hub. <!--TODO MQTT allow anonymous access to the hub-->
13-
14-
If client library doesn't accept a URI, then you probably need to split the information in the URI into multiple parameters:
15-
16-
* Host: `{serviceName}.webpubsub.azure.com`
17-
* Path: `/clients/mqtt/hubs/{hub}?access_token={token}`
18-
* Port: 443
19-
* Transport: WebSockets with [TLS](https://wikipedia.org/wiki/Transport_Layer_Security).
20-
219
There are some limitations you should follow in your [MQTT](https://mqtt.org/mqtt-specification/) clients, otherwise the connection will be rejected. These MQTT protocol parameters include:
2210
* Protocol versions: 3.1.1 or 5.0.
2311
* Client ID format
44.7 KB
Loading

articles/azure-web-pubsub/overview-mqtt.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ You can use MQTT protocols in Web PubSub service for the following scenarios:
2424

2525
**Standard MQTT Protocols Support**:
2626

27-
Web PubSub service supports MQTT 3.1.1 and 5.0 protocols in a standard way that any MQTT SDK that support WebSocket transport can connect to Web PubSub. Users who wish to use Web PubSub in a programming language that doesn't have a native Web PubSub SDK can still connect and communicate using MQTT.
27+
Web PubSub service supports MQTT 3.1.1 and 5.0 protocols in a standard way that any MQTT SDK with WebSocket transport support can connect to Web PubSub. Users who wish to use Web PubSub in a programming language that doesn't have a native Web PubSub SDK can still connect and communicate using MQTT.
2828

29-
**Communication Between Various Protocols**:
29+
**Cross-Protocol Communication**:
3030

3131
MQTT clients can communicate with clients of other Web PubSub protocols. Find more details [here](./reference-mqtt-cross-protocol-communication.md)
3232

articles/azure-web-pubsub/quickstarts-pubsub-among-mqtt-clients.md

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ This quickstart guide demonstrates how to
2424
- Install the dependencies for the language you plan to use
2525

2626
> [!NOTE]
27-
> Except for the MQTT client libraires mentioned belows, you can choose any standard MQTT client libraries that meet the following requirements to connect to Web PubSub:
27+
> Except for the MQTT client libraries mentioned belows, you can choose any standard MQTT client libraries that meet the following requirements to connect to Web PubSub:
2828
> 1. Support WebSocket transport.
2929
> 2. Support MQTT protocol 3.1.1 or 5.0.
3030
@@ -62,21 +62,17 @@ pip install paho-mqtt
6262

6363
## Connect to Web PubSub
6464

65-
[!INCLUDE [MQTT-Connection-Parameters](includes/mqtt-connection-Parameters.md)]
65+
An MQTT uses a **Client Access URL** to connect and authenticate with your resource. This URL follows a pattern of `wss://<service_name>.webpubsub.azure.com/clients/mqtt/hubs/<hub_name>?access_token=<token>`.
6666

67-
A client can have a few ways to obtain the Client Access URL. For this quick start, you generate the access token with a CLI tool. It's best practice to not hard code the Client Access URL in your code. In the production world, we usually set up an app server to return this URL on demand. [Generate Client Access URL](./howto-generate-client-access-url.md) describes the practice in detail.
67+
A client can have a few ways to obtain the Client Access URL. It's best practice to not hard code the Client Access URL in your code. In the production world, we usually set up an app server to return this URL on demand. [Generate Client Access URL](./howto-generate-client-access-url.md) describes the practice in detail.
6868

69-
<!--TODO Replace with portal token generation tool after it's implemented-->
69+
For this quick start, you can copy and paste one from Azure portal shown in the following diagram.
7070

71-
```powershell
72-
npm install -g jwtgen
73-
jwtgen -a HS256 -s "{webpubsub_access_key}" -c "aud=wss://{service_name}.webpubsub.azure.com/clients/mqtt/hubs/{hub_name}" -c 'role=["webpubsub.sendToGroup","webpubsub.joinLeaveGroup"]' -e 3600000
74-
```
71+
![The diagram shows how to get MQTT client access url.](./media/quickstarts-pubsub-among-mqtt-clients/portal-mqtt-client-access-uri-generation.png)
7572

76-
> [!NOTE]
77-
> This step will be replaced by the client generation tool on Azure Portal once it's implemented. If you're using other shells, make sure each element of the roles surrounded by double quotation marks.
73+
As shown in the preceding code, the client has the permissions to send messages to topic `group1` and to subscribe to topic `group2`.
7874

79-
As shown in the preceding code, the client has the permissions to send messages to and subscribe to any topic.
75+
[!INCLUDE [MQTT-Connection-Parameters](includes/mqtt-connection-Parameters.md)]
8076

8177
The following code shows how to connect MQTT clients to WebPubSub with MQTT protocol version 5.0, clean start, 30-seconds session expiry interval.
8278

@@ -159,7 +155,7 @@ To receive messages from topics, the client
159155
- must subscribe to the topic it wishes to receive messages from
160156
- has a callback to handle message event
161157

162-
The following code shows a client subscribes to topics named `topic1`.
158+
The following code shows a client subscribes to topics named `group2`.
163159

164160
# [JavaScript](#tab/javascript)
165161

@@ -168,11 +164,11 @@ The following code shows a client subscribes to topics named `topic1`.
168164

169165
// Provide callback to the message event.
170166
client.on("message", async (topic, payload, packet) => {
171-
concole.log(topic, payload)
167+
console.log(topic, payload)
172168
});
173169

174-
// Subscribe to a topic "topic".
175-
client.subscribe("topic1", { qos: 1 }, (err, granted) => { console.log("subscribe", granted); })
170+
// Subscribe to a topic.
171+
client.subscribe("group2", { qos: 1 }, (err, granted) => { console.log("subscribe", granted); })
176172

177173
```
178174

@@ -182,13 +178,13 @@ client.subscribe("topic1", { qos: 1 }, (err, granted) => { console.log("subscrib
182178
// ...code from the last step
183179
184180
// Provide callback to the message event.
185-
mqttClient.ApplicationMessageReceivedAsync += (args) =>
181+
client.ApplicationMessageReceivedAsync += (args) =>
186182
{
187183
Console.WriteLine($"Received message on topic '{args.ApplicationMessage.Topic}': {System.Text.Encoding.UTF8.GetString(args.ApplicationMessage.PayloadSegment)}");
188184
return Task.CompletedTask;
189185
};
190186
// Subscribe to a topic "topic".
191-
await mqttClient.SubscribeAsync("topic1", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
187+
await client.SubscribeAsync("group2", MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
192188
```
193189

194190
# [Python](#tab/python)
@@ -202,7 +198,7 @@ def subscriber_on_message(client, userdata, msg):
202198
client.on_message = subscriber_on_message
203199

204200
# Subscribe to a topic "topic".
205-
client.subscribe("topic1")
201+
client.subscribe("group2")
206202

207203
# Blocking call that processes network traffic, dispatches callbacks and
208204
# handles reconnecting.
@@ -214,33 +210,33 @@ client.loop_forever()
214210
---
215211

216212
## Publish a message to a group
217-
In the previous step, we've set up everything needed to receive messages from `topic1`, now we send messages to that group.
213+
In the previous step, we've set up everything needed to receive messages from `group1`, now we send messages to that group.
218214

219215
# [JavaScript](#tab/javascript)
220216

221217
```javascript
222218
// ...code from the last step
223219

224-
// Send message "Hello World" in the "text" format to "topic1".
225-
client.publish("topic1", "Hello World!")
220+
// Send message "Hello World" in the "text" format to "group1".
221+
client.publish("group1", "Hello World!")
226222
```
227223

228224
# [C#](#tab/csharp)
229225

230226
```csharp
231227
// ...code from the last step
232228
233-
// Send message "Hello World" in the "text" format to "topic1".
234-
await client.PublishStringAsync("topic1", "Hello World!");
229+
// Send message "Hello World" in the "text" format to "group1".
230+
await client.PublishStringAsync("group1", "Hello World!");
235231
```
236232

237233
# [Python](#tab/python)
238234

239235
```python
240236
# ...code from the last step
241237

242-
# Send message "Hello World" in the "text" format to "topic1".
243-
client.publish("topic1", "Hello World!")
238+
# Send message "Hello World" in the "text" format to "group1".
239+
client.publish("group1", "Hello World!")
244240
```
245241
---
246242

0 commit comments

Comments
 (0)