Mqtt连接为AWS IOT预签名URL提供403

时间:2018-07-25 09:58:47

标签: websocket mqtt iot http-status-code-403 aws-iot

我有aws lambda函数,可生成如下所示的IOT Websocket URL。

const v4 = require('aws-signature-v4');
const crypto = require('crypto');

const WSSURL = v4.createPresignedURL(
        'GET',
        process.env.IOT_ENDPOINT_HOST.toLowerCase(),
        '/mqtt',
        'iotdevicegateway',
        crypto.createHash('sha256').update('', 'utf8').digest('hex'),
        {
            'key': process.env.IOT_ACCESS_KEY,
            'secret': process.env.IOT_SECRET_KEY,
            'protocol': 'wss',
            'region': process.env.IOT_AWS_REGION,
        }
    );

并且我在客户端使用该网址的mqttjs并尝试按以下方式连接Web套接字。

var options = {
        will    : {
            topic  : LAST_WILL_TOPIC,
            payload: getMessageString(wss_userId, wss_email, wss_userType, {})
        },
        clientId: wss_userType + '||' + wss_userId
    };

    wssClient = mqtt.connect(WSSURL, options); 

此代码在几个月前运行良好,但现在连接无法启动,并出现以下错误

failed: Error during WebSocket handshake: Unexpected response code: 403

1 个答案:

答案 0 :(得分:3)

我们的团队最近也遇到了这个问题。

版本为1.2.0的aws-signature-v4模块中的问题。

这里是code

`options.sessionToken = options.sessionToken || process.env.AWS_SESSION_TOKEN;` 

默认情况下,AWS lambda在AWS_SESSION_TOKEN中有一个process.env

您应该使用STS担任角色并使用其中的sessionToken

import v4 from 'aws-signature-v4' // ^1.3.0
import STS from 'aws-sdk/clients/sts'

const { IOT_ENDPOINT_HOST, IOT_ROLE_ARN } = process.env
const sts = new STS()

const createSocketUrl = async () => {
  const data = await sts
    .assumeRole({
      RoleArn: IOT_ROLE_ARN,
      RoleSessionName: `some-role-session-name`,
      DurationSeconds: 3600
    })
    .promise()

  return v4.createPresignedURL(
    'GET',
    IOT_ENDPOINT_HOST,
    '/mqtt',
    'iotdevicegateway',
    '',
    {
      key: data.Credentials.AccessKeyId,
      secret: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken,
      protocol: 'wss'
    }
  )
}

或者如果您不想使用STS

import v4 from 'aws-signature-v4' // ^1.3.0

const { IOT_ENDPOINT_HOST, IOT_ACCESS_KEY_ID, IOT_SECRET_ACCESS_KEY } = process.env

const createSocketUrl = () => {
  const { AWS_SESSION_TOKEN } = process.env

  delete process.env['AWS_SESSION_TOKEN']

  const url = v4.createPresignedURL(
    'GET',
    IOT_ENDPOINT_HOST,
    '/mqtt',
    'iotdevicegateway',
    '',
    {
      key: IOT_ACCESS_KEY_ID,
      secret: IOT_SECRET_ACCESS_KEY,
      protocol: 'wss'
    }
  )
  process.env['AWS_SESSION_TOKEN'] = AWS_SESSION_TOKEN

  return url
}