Search code examples
amazon-web-servicesflutteramazon-lex

Amazon Lex authorization with Flutter


I want write Flutter app which work with Amazon Lex REST API.Amazon has specific way for authenticating I used SigV4 package to make required headers

  Sigv4Client client = Sigv4Client(
  keyId: kAccessKey,
  accessKey: kSecretKey,
  region: "us-east-1",
  serviceName: "lex",
);

final request = client.request(
  "https://runtime.lex.us-east-1.amazonaws.com/bot/myBotName/alias/BETA/user/myUserId/text",
  method: 'POST',
  body: jsonEncode({'inputText': 'hi'}),
);

var response=post(request.url, headers: request.headers, body: request.body);
print(response.body);

but i get this message in print :

{"message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}

I get valid response on postman with same data the only part is different in postman and this package is "X-Amz-Content-Sha256" value and of course Signature value (it change every time) . "X-Amz-Content-Sha256" postman value:

beaead3198f7da1e70d03ab969765e0821b24fc913697e929e726aeaebf0eba3

"X-Amz-Content-Sha256" my code value:

ee9ef87bd5a357cff93b1d83d1e8a1b47fb3fa2e94251711c6a30250119e6369

I tried to write function to calculate authenticating string but it was so complex for me .


Solution

  • I changed the package and use amazon-cognito-identity-dart-2

    and send the request like this :

    AwsSigV4Client client=AwsSigV4Client(
          kAccessKey,
          kSecretKey,
          'https://runtime.lex.us-east-1.amazonaws.com',
          region: 'us-east-1',
          serviceName: 'lex',
        );
    
    final signedRequest = new SigV4Request(
          client,
          method: 'POST',
          path: '/bot/MyBotName/alias/BETA/user/MyUser/text',
          headers: new Map<String, String>.from({
            'Content-Type': 'application/json; charset=utf-8',
            'ACCEPT': 'application/json',
          }),
          body: new Map<String, dynamic>.from({"inputText": "hi"}),
        );
    
    var response = await http.post(
          signedRequest.url,
          headers: signedRequest.headers,
          body: signedRequest.body,
        );
    

    it so important to add

    'Content-Type': 'application/json; charset=utf-8',
    

    in your headers .