我已经使用 WebSocket 协议(protocol)设置了一个 API 网关。在“$connect”路由请求设置中,我选择了“AWS_IAM”作为授权方法。用户通过 Cognito 登录后,Web 应用程序需要与此 WebSocket API 建立连接。然后,我如何从 Web 应用程序上的 JavaScript 授权 WebSocket API 请求?使用 HTTP API 网关,我可以从传递到请求 header 的访问 key 和 session token 生成签名。但我无法在 WebSocket 请求中传递 header 。
最佳答案
这是一些适用于我的示例/伪代码:
使用 AWS Amplify 认证用户:
import { w3cwebsocket as W3CWebSocket } from "websocket"
import { Auth, Signer } from "aws-amplify"
let wsClient: any = null
export const client = async () => {
if (wsClient) return wsClient
if ((await Auth.currentUserInfo()) === null) return wsClient
const credentials = await Auth.currentCredentials()
const accessInfo = {
access_key: credentials.accessKeyId,
secret_key: credentials.secretAccessKey,
session_token: credentials.sessionToken,
}
const wssUrl = "wss://YOUR-API-ID.execute-api.REGION.amazonaws.com/dev"
const signedUrl = Signer.signUrl(wssUrl, accessInfo)
wsClient = new W3CWebSocket(signedUrl)
wsClient.onerror = function () {
console.log("[client]: Connection Error")
}
wsClient.onopen = function () {
console.log("[client]: WebSocket Client Connected")
}
wsClient.onclose = function () {
console.log("[client]: Client Closed")
}
wsClient.onmessage = function (e: any) {
if (typeof e.data === "string") {
console.log("Received: '" + e.data + "'")
}
}
return wsClient
}
然后使用 AWS Cognito 也需要此权限:
{
"Action": ["execute-api:Invoke"],
"Resource": "arn:aws:execute-api:REGION:ACCOUNT-ID-OR-WILDCARD:*/*/$connect",
"Effect": "Allow"
}
关于amazon-web-services - 使用 AWS_IAM 向 AWS WebSocket API 网关授权请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964548/