Lambda 함수 정의 - AWS IoT Core

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Lambda 함수 정의

가 권한 부여자를 AWS IoT Core 호출하면 다음 JSON 객체가 포함된 이벤트가 있는 권한 부여자와 연결된 Lambda가 트리거됩니다. 예제 JSON 객체에는 가능한 모든 필드가 포함되어 있습니다. 연결 요청과 관련이 없는 필드는 포함되지 않습니다.

{     "token" :"aToken",     "signatureVerified": Boolean, // Indicates whether the device gateway has validated the signature.     "protocols": ["tls", "http", "mqtt"], // Indicates which protocols to expect for the request.     "protocolData": {         "tls" : {             "serverName": "serverName" // The server name indication (SNI) host_name string.         },         "http": {             "headers": {                 "#{name}": "#{value}"             },             "queryString": "?#{name}=#{value}"         },         "mqtt": {             "username": "myUserName",             "password": "myPassword", // A base64-encoded string.             "clientId": "myClientId" // Included in the event only when the device sends the value.         }     },     "connectionMetadata": {         "id": UUID // The connection ID. You can use this for logging.     }, }

Lambda 함수는 이 정보를 사용하여 들어오는 연결을 인증하고 연결에 허용되는 작업을 결정해야 합니다. 함수는 다음 값을 포함하는 응답을 전송해야 합니다.

  • isAuthenticated: 요청 인증 여부를 나타내는 부울 값입니다.

  • principalId: 사용자 지정 권한 부여 요청에서 전송되는 토큰의 식별자 역할을 하는 영숫자 문자열입니다. 값은 1~128자의 영숫자 문자열이어야 하며 정규식(regex) 패턴 ([a-zA-Z0-9]){1,128}과 일치해야 합니다. 영숫자가 아닌 특수 문자는 principalId에서 와 함께 사용할 수 없습니다 AWS IoT Core. 에 영숫자가 아닌 특수 문자가 허용되는 경우 다른 AWS 서비스에 대한 설명서를 참조하세요principalId.

  • policyDocuments: JSON형식이 지정된 AWS IoT Core 정책 문서 목록 AWS IoT Core 정책 생성에 대한 자세한 내용은 섹션을 참조하세요AWS IoT Core 정책. 정책 문서의 최대 수는 10개의 정책 문서입니다. 각 정책 문서는 최대 2,048자를 포함할 수 있습니다.

  • disconnectAfterInSeconds: AWS IoT Core 게이트웨이에 대한 연결의 최대 지속 시간(초)을 지정하는 정수입니다. 최소값은 300초이고 최대값은 86,400초입니다. 기본값은 86,400입니다.

    참고

    disconnectAfterInSeconds (Lambda 함수에서 반환됨) 값은 연결이 설정될 때 설정됩니다. 후속 정책 새로 고침 Lambda 호출 중에는 이 값을 수정할 수 없습니다.

  • refreshAfterInSeconds: 정책 새로 고침 사이의 간격을 지정하는 정수입니다. 이 간격이 경과하면 AWS IoT Core 은(는) Lambda 함수를 호출하여 정책 새로 고침을 허용합니다. 최소값은 300초이고 최대값은 86,400초입니다.

 다음 JSON 객체에는 Lambda 함수가 전송할 수 있는 응답의 예가 포함되어 있습니다.

{ "isAuthenticated":true, //A Boolean that determines whether client can connect. "principalId": "xxxxxxxx",  //A string that identifies the connection in logs. "disconnectAfterInSeconds": 86400,  "refreshAfterInSeconds": 300,   "policyDocuments": [       {         "Version": "2012-10-17",         "Statement": [            {               "Action": "iot:Publish",               "Effect": "Allow",               "Resource": "arn:aws:iot:us-east-1:<your_aws_account_id>:topic/customauthtesting"             }          ]        }     ] }

policyDocument 값에는 유효한 AWS IoT Core 정책 문서가 포함되어야 합니다. AWS IoT Core 정책에 대한 자세한 내용은 섹션을 참조하세요AWS IoT Core 정책. MQTT 과 TLS MQTT 이상의 WebSockets 연결에서 refreshAfterInSeconds 필드 값에 지정된 간격 동안 이 정책을 AWS IoT Core 캐시합니다. HTTP 연결의 경우 디바이스가 HTTP 영구 연결(HTTP지속 연결 또는 연결 HTTP 재사용이라고도 함)을 사용하지 않는 한 모든 권한 부여 요청에 대해 Lambda 함수가 호출됩니다. 권한 부여자를 구성할 때 캐싱을 활성화하도록 선택할 수 있습니다. 이 간격 동안 는 Lambda 함수를 다시 트리거하지 않고 이 캐시된 정책에 대해 설정된 연결의 작업을 AWS IoT Core 승인합니다. 사용자 지정 인증 중에 장애가 발생하면 는 연결을 AWS IoT Core 종료합니다. AWS IoT Core 또한 는 disconnectAfterInSeconds파라미터에 지정된 값보다 오래 열려 있는 경우 연결을 종료합니다.

다음은 값이 인 MQTT 연결 메시지에서 암호를 찾고 이름이 인 클라이언트 AWS IoT Core 와 연결하고 동일한 클라이언트 이름이 포함된 주제에 myClientName 게시할 수 있는 권한을 부여하는 정책을 test 반환하는 샘플 Node.js Lambda 함수를 JavaScript 포함합니다. 예상된 암호를 찾지 못하면 이 두 작업을 거부하는 정책을 반환합니다.

// A simple Lambda function for an authorizer. It demonstrates // how to parse an MQTT password and generate a response. exports.handler = function(event, context, callback) {     var uname = event.protocolData.mqtt.username;     var pwd = event.protocolData.mqtt.password;     var buff = new Buffer(pwd, 'base64');     var passwd = buff.toString('ascii');     switch (passwd) {         case 'test':             callback(null, generateAuthResponse(passwd, 'Allow')); break;         default:             callback(null, generateAuthResponse(passwd, 'Deny'));       } }; // Helper function to generate the authorization response. var generateAuthResponse = function(token, effect) { var authResponse = {}; authResponse.isAuthenticated = true; authResponse.principalId = 'TEST123'; var policyDocument = {}; policyDocument.Version = '2012-10-17'; policyDocument.Statement = []; var publishStatement = {}; var connectStatement = {}; connectStatement.Action = ["iot:Connect"]; connectStatement.Effect = effect; connectStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:client/myClientName"]; publishStatement.Action = ["iot:Publish"]; publishStatement.Effect = effect; publishStatement.Resource = ["arn:aws:iot:us-east-1:123456789012:topic/telemetry/myClientName"]; policyDocument.Statement[0] = connectStatement; policyDocument.Statement[1] = publishStatement; authResponse.policyDocuments = [policyDocument]; authResponse.disconnectAfterInSeconds = 3600; authResponse.refreshAfterInSeconds = 300; return authResponse; }

이전 Lambda 함수는 MQTT 연결 메시지test에서 의 예상 암호를 수신JSON하면 다음을 반환합니다. passwordprincipalId 속성의 값은 MQTT 연결 메시지의 값입니다.

{ "password": "password", "isAuthenticated": true, "principalId": "principalId", "policyDocuments": [ { "Version": "2012-10-17", "Statement": [ { "Action": "iot:Connect", "Effect": "Allow", "Resource": "*" }, { "Action": "iot:Publish", "Effect": "Allow", "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}" }, { "Action": "iot:Subscribe", "Effect": "Allow", "Resource": "arn:aws:iot:region:accountId:topicfilter/telemetry/${iot:ClientId}" }, { "Action": "iot:Receive", "Effect": "Allow", "Resource": "arn:aws:iot:region:accountId:topic/telemetry/${iot:ClientId}" } ] } ], "disconnectAfterInSeconds": 3600, "refreshAfterInSeconds": 300 }