To connect to an AWS IoT broker using WebSocket authentication, you must sign your initial request using AWS Signature V4. This is typically done using the AWSSigner from the Soto library.
- Define your AWS IoT endpoint host.
- Create an
AWSSigner with your credentials, the service name iotdata, and your target region. - Sign the URL for the
/mqtt path. - Construct the
requestURI by appending the signed query parameters to the path. - Use
MQTTConnection.withConnection with a .webSocket transport configuration, passing the requestURI as the urlPath.
import SotoSignerV4
import MQTTNIO
let host = "MY_AWS_IOT_ENDPOINT.iot.eu-west-1.amazonaws.com"
let headers = HTTPHeaders([("host", host)])
let signer = AWSSigner(
credentials: StaticCredential(accessKeyId: "MYACCESSKEY", secretAccessKey: "MYSECRETKEY"),
name: "iotdata",
region: "eu-west-1"
)
let signedURL = signer.signURL(
url: URL(string: "https://\(host)/mqtt")!,
method: .GET,
headers: headers,
body: .none,
expires: .minutes(30)
)
let requestURI = "/mqtt?\(signedURL.query!)"
try await MQTTConnection.withConnection(
address: .hostname(host),
configuration: .init(transport: .webSocket(.init(urlPath: requestURI), tls: .enable(...))),
identifier: "My AWS Client"
) { connection in
// You are now connected to AWS IoT
}