The example in the aws tutorial does not show the login method via mqtt with username and password. How can I connect with Custom Authentication using username and password?
I tried with custom authentication but it didn’t work.
- I tried to create custom authontication with port 443 without using X.509 certificate. link: https://docs.aws.amazon.com/iot/latest/developerguide/protocols.html
-
I followed the steps in the aws docs. I edited some parts for login with MQTT username and password.
link : https://docs.aws.amazon.com/iot/latest/developerguide/config-custom-auth.html
-
This is my Lambda Function (arn addresses are correct)
// A simple Lambda function for an authorizer. 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')); 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:eu-west-1:<myarn>:client/myClientName"]; publishStatement.Action = ["iot:Publish"]; publishStatement.Effect = effect; publishStatement.Resource = ["arn:aws:iot:eu-west-1:<myarn>:topic/telemetry/myClientName"]; policyDocument.Statement[0] = connectStatement; policyDocument.Statement[1] = publishStatement; authResponse.policyDocuments = [policyDocument]; authResponse.disconnectAfterInSeconds = 3600; authResponse.refreshAfterInSeconds = 300; return authResponse; }
2
Answers
AWS IoT Core really wants you to use a client certificate to connect to the MQTT broker.
Alternately you can have your server generate a signature version 4 url using your access key id and secret access key for an authorized user. I don’t like this way, but it works in a pinch. See https://glitch.com/edit/#!/itp-arduino-workshop?path=AWS-IoT-ws-url.js for one way to do this.
A better way is to setup Cognito to allow access to IoT Core. The AWS Innovator Island tutorial demonstrates how to do this. See the backend section of part 2 for more details.
I made it work the sample authorizer code with the following client. No encoding is required for the password.
Do you see any error in your logs?
aws logs tail --follow AWSIotLogsV2
aws logs tail --follow /aws/lambda/AuthorizerFunctionName