aws-samples / simple-websockets-chat-app

This SAM application provides the Lambda functions, DynamoDB table, and roles to allow you to build a simple chat application based on API Gateway's new WebSocket-based API feature.
MIT No Attribution
682 stars 280 forks source link

Response {"message": "Forbidden", ...} #24

Closed Adnan-Shahid closed 4 years ago

Adnan-Shahid commented 5 years ago

I directly deployed this project through aws, and deployed it, I can connect using wscat -c url, but when I try to send any message I get a response (with actual strings for connectionid and request id): {"message": "Forbidden", "connectionId":"some_string", "requestId":"some_string"}

Is there a step that needs to be applied outside of the deployment that is not documented? (I did definitely deploy the api and stage it)

frontr-uk commented 5 years ago

same here, can't figure out. Did u find an answer @Adnan-Shahid

Adnan-Shahid commented 5 years ago

I haven't been able to find the cause yet either unfortunately

frontr-uk commented 5 years ago

Hey Adnan, give me a ping on chris@frontr.co.uk and lets get connected so I can share you what i did to make it work. I just don't have time to write it up

dgomesbr commented 5 years ago

hey @frontr-uk @Adnan-Shahid, I'm in paternity leave, if you can, share the details here and we'll incorporate on the repo. Thank you

Adnan-Shahid commented 5 years ago

@frontr-uk It appears more than just us have this issue, it would be great if you could share how you solved it here for everyone

markotitel commented 5 years ago

Also had the same issue. Searching through closed issues helped me. The same issue is opened and the answer is at the bottom https://github.com/aws-samples/simple-websockets-chat-app/issues/23

SendMessage lambda needs to be built before deployment. Use npm install and then the procedure is the same.

Actually there are two errors that may occur, at least those two I've noticed so far. First is {"message": "Internal server error", "connectionId":"Zo4APfrwIAMCK8w=", "requestId":"Zo4BOG05oAMF9dA="}. When you look to CloudWatch logs /aws/lambda/simple-websocket-chat-app-OnDisconnectFunction-* you'll notice issue with AWS-SDK and require('aws-sdk/clients/apigatewaymanagementapi') this issue is similar https://github.com/aws/aws-sdk-js/issues/2520 This error is solved by npm install in sendmessage directory. Then sam package and sam deploy.

The other error is basically not sending proper payload. Check your request json data. This is proper one {"message":"sendmessage", "data":"hello world"} Maybe you have something like "message":"sendMessage", "data":"hello world"} Or { "action": "sendmessage", “data”: "Hello, I am using WebSocket APIs in API Gateway.” }.

markotitel commented 5 years ago

You can checkout this PR https://github.com/aws-samples/simple-websockets-chat-app/pull/25 This should work out of the box.

dgomesbr commented 5 years ago

fixed by #25

Adnan-Shahid commented 5 years ago

This doesn't seem to be fixed when deploying directly from AWS's Serverless Application Respository. I get the same error

dgomesbr commented 5 years ago

@jt0 could sync it again or grant me privileges to do so?

aushakov95 commented 5 years ago

@dgomesbr @markotitel Deploying via the AWS CLI produces the same error for me. {"message": "Forbidden", "connectionId":"connectionId_here", "requestId":"requestid_here"}

markotitel commented 5 years ago

@aushakov95 Have you deployed from serverless repo or from github?

carnivaloftrees commented 5 years ago

@aushakov95 Have you deployed from serverless repo or from github?

I have personally tried both and I have the "Forbidden" error each time :(

aushakov95 commented 5 years ago

@markotitel @carnivaloftrees Yes I have tried both. But I figured out why it was not working for me! I was sending this via wscat {"action": "sendmessage"...} per instructions on the aws guide for this repo.

So what fixed it for me was typing in {"message": "sendmessage"...} instead.

carnivaloftrees commented 5 years ago

@aushakov95 Really? Because I just tried with what you've just said and I still get the same error: {"message": "sendmessage","data": "test"} {"message": "Forbidden", ...}

Am I still missing something?

Thanks for the suggestion though, it gives me a lead at least.

carnivaloftrees commented 5 years ago

Is my wscat connection ok?

wscat -c wss://(ID).execute-api.(REGION).amazonaws.com/Prod

aushakov95 commented 5 years ago

@carnivaloftrees

Your connection url is right.

This is a bit of a long shot, but go to the sendmessage route inside API Gateway and click “add integration response”. Try again

carnivaloftrees commented 5 years ago

@carnivaloftrees

Your connection url is right.

This is a bit of a long shot, but go to the sendmessage route inside API Gateway and click “add integration response”. Try again

Still giving me forbidden! What do you pass through as data? Just anything? Thanks for help by the way, I appreciate it, I really want to be able to use the websocket.

ngPati commented 5 years ago

Same issue here :(

acahinton commented 5 years ago

Anyone still having this issue deploying via the AWS SAR - the code does not currently reflect the master branch here so you can make the following changes to resolve:

In the "sendMessage" lambda; change the runtime to node 10 and remove the following line from the sendmessage/app.js

image

Deploying via the command line using AWS SAM works fine from a download of the current master branch code.

hsmr29 commented 5 years ago

@acahinton

I did what you said, but I still see the same error as the others. Forbidden

ngPati commented 5 years ago

@acahinton Node 10.x fixed the issue for me :)

acahinton commented 5 years ago

@Hugosimon29 - I take it you are formatting the message as follows:

{"message":"sendmessage", "data":"hello world"}

If so, it might be worth deleting your cloudformation stack for this sample, then re-adding via AWS SAR and making the above two small changes to see if that helps?

I've now set up deployments from Bitbucket calling the SAM CLI to deploy and it's working fine as a base that I can then develop from. Is that an option (or similar) given that the AWS SAR latest build is broken?

dgomesbr commented 5 years ago

I'm back from leave, took ownership of the SAR, will review and sync repo/publish app next week, sorry about the whole problem and lack of attention folks.

XJIOP commented 5 years ago
> {"message":"sendmessage", "data":"hello world"}
< {"message": "Forbidden", "connectionId":"bkxyKepxLPECH6g=", "requestId":"bkxzcGywrPEFstw="}

problem in "sendmessage" should be "sendMessage"

iDevo commented 5 years ago

Hey guys! I deployed the app using AWS directly and faced the same issue. In a conclusion to all mentioned possible solutions I tested 3 different code changes:

  1. Original version with Node 8
  2. Applied changes from @acahinton with Node 10 and commented line 7 in sendmessage
  3. Applied the changes from the GitHub commit #25 from May 13 manually to the websocket-chat-app

Each time testing all of the following parameter using wscat:

{“action”:“sendMessage”, “data”:“hello world”}
{“action”:“sendmessage”, “data”:“hello world”}
{“message”:“sendMessage”, “data”:“hello world”}
{“message”:“sendmessage”, “data”:“hello world”}

Unfortunately nothing helped so far and I am still getting the error message in the terminal: {"message": "Forbidden", "connectionId":"<ID>=", "requestId":"<ID>"}

I also tried to debug the app myself but the sendmessage function seems to not be triggered at any time, while the connecting and disconnecting works like a charm. I could not find any problems in the API Gateway but in my opinion the issue might be located in there there.

Cheers!

autoCAT6 commented 5 years ago

Guys if you're still having that "message: Forbidden" error on "sendmessage" route, it's probably because you didn't capitalize that "M". I changed my lambda function runtime to Node.js 10.x and deleted that require statement in app.js, then sent my json payload as "{"message":"sendMessage","data":"hello"}". Everything worked perfectly.

hardingmatt commented 5 years ago

Thanks- changing {"action":"sendmessage", "data":"hello world"} to {"message":"sendMessage", "data":"hello world"} was all I needed.

@dgomesbr Would it be possible to edit the blog post to reflect this change? Thank you!

https://aws.amazon.com/blogs/compute/announcing-websocket-apis-in-amazon-api-gateway/

DaisukeNagata commented 5 years ago

https://twitter.com/i/status/1146440093046996993

Double quotes are automatically changed on Mac Notepad. so I could not chat. And I did. Thank you very much.

pilgrim2go commented 5 years ago

I deployed using serverless console and got the same issue. Fix 1

changing {"action":"sendmessage", "data":"hello world"} to {"message":"sendMessage", "data":"hello world"}

Another issue

{"message": "Internal server error", "connectionId":"Zo4APfrwIAMCK8w=", "requestId":"xxx="}

Fix 2 I have to run cd /simple-websockets-chat-app/sendmessage npm install zip -r package.zip . and then update sendMessage Lambda to solve the issue

Gharaibeh commented 4 years ago

I tried to send after connect : {"message":"sendMessage","data":"hello"} But I got this error as reply: < {"message": "Internal server error", "connectionId":"-----", "requestId":"-----"}

appindus-kanderson commented 4 years ago

There were a number of helpful comments above. After troubleshooting for a bit I was able to successfully connect and send a message with the following configuration:

// Log messages from the server connection.onmessage = function (e) { console.log('Server: ' + e.data); };


Hope this helps.
fimbox commented 4 years ago

I set up the pipeline with a simple custom lambda function without the SAR deployment: exports.handler = async (event, context) => { const response = { statusCode: 200, body: JSON.stringify('Hello from Lambda!'), }; return response; }; I constantly got the "message": "forbidden" answer with wscat.

I finally solved the issue by using $request.body.message instead of $request.body.action in the Route Selection Expression.

Of course we also need to send the matching route key like "sendMessage" instead of "onmessage"

grafik

thatguyfig commented 4 years ago

Hi all,

Today I deployed this template from the SAR, and had to do the following to get this to work correctly.

  1. Take note of the Route setup - i.e. check the names of the following: image

  2. This means you will have to modify your input JSON within wscat to accomodate these differences. i.e: {"message": "sendMessage", "data": "message to send to other clients"}

  3. Changing only this, your error will move from Forbidden to Internal Server Error. To overcome this, do as mentioned by @acahinton https://github.com/aws-samples/simple-websockets-chat-app/issues/24#issuecomment-500393045 3a. Comment out line for aws-sdk require 3b. Update Lambda Function to use Node.Js 10

  4. Redeploy your API to the target stage and you should now be able to send and receive data from different clients without errors.

Let me know if that doesn't work because it definitely did for me.

Thanks, Tom

Ronald-Saunfe commented 4 years ago

Thanks a lot it worked but i had to create a new Websocket API since i could not change the route from '$request.body.action' to '.message'

iqdavidh commented 4 years ago

Hi, I had the same issue, This changes allows to get it works

https://github.com/iqdavidh/simple-websockets-chat-app

I changed the api gateway acording to another example.

SahajRana commented 4 years ago

Using Deploy Api again from Actions, after adding a new route, did the trick for me.

jagadish432 commented 4 years ago

1) For the error "Forbidden" : -> When you send the request {"action": "", "message": "some text "}, make sure that the first key ("action" here ) is based on the value of "route selection expression" you gave in API gateway i.e., for MY above example request to work, the route selection expression should be "$request.body.action".

2) For the error "Internal server error": -> a) Give proper required "cloudwatch logs access" to the role which you applied for the AWS Lambda functions. b) Check the logs so that your lambda function should n't fail i.e., dependencies should be given correctly, exception handling and provide some print statements for better debugging. c) API gateway will return 504(if lambda takes more time than 30 seconds which means gateway will time out) and 502(if lambda doesn't give a proper response which gateway can understand)

Note: lambda should provide a response in the form of { "statusCode": 200, "<message/result>": "some result response text"} in case of python ( "callback(None, response) in case of NoeJS, I'm not sure about other languages )

Let me know if this solves for you, reply back if the error still occurs.

soumilshah1995 commented 4 years ago
  • require('aws-sdk/clients/apigatewaymanagementapi');

Hi all,

Today I deployed this template from the SAR, and had to do the following to get this to work correctly.

  1. Take note of the Route setup - i.e. check the names of the following: image
  2. This means you will have to modify your input JSON within wscat to accomodate these differences. i.e: {"message": "sendMessage", "data": "message to send to other clients"}
  3. Changing only this, your error will move from Forbidden to Internal Server Error. To overcome this, do as mentioned by @acahinton #24 (comment) 3a. Comment out line for aws-sdk require 3b. Update Lambda Function to use Node.Js 10
  4. Redeploy your API to the target stage and you should now be able to send and receive data from different clients without errors.

Let me know if that doesn't work because it definitely did for me.

Thanks, Tom

I am using Python Lambda and getting internal Server Error can anyone Help i followed all steps showed in Github Comments

soumilshah1995 commented 4 years ago

Anyone still having this issue deploying via the AWS SAR - the code does not currently reflect the master branch here so you can make the following changes to resolve:

In the "sendMessage" lambda; change the runtime to node 10 and remove the following line from the sendmessage/app.js

  • require('aws-sdk/clients/apigatewaymanagementapi');

image

Deploying via the command line using AWS SAM works fine from a download of the current master branch code. Whats the solution for people who are using python Lambda Function

oscarnevarezleal commented 4 years ago

Ha! For some reason the last version of this repo I use created sendmessage (mind the lowercase) so my payload needed to look like this {"message": "sendmessage", "data": "message to send to other clients"}

Works fine.

dgomesbr commented 4 years ago

The SAR is out-of-date, I'm on leave, as soon as I'm back I'll clean the issues, publish a new version of the SAR and update the blog post.

Thanks for the patience.

jonathanmv commented 4 years ago

Ha! For some reason the last version of this repo I use created sendmessage (mind the lowercase) so my payload needed to look like this {"message": "sendMessage", "data": "message to send to other clients"}

Works fine.

I'm using all-lowercase sendmessage and it works for me

dgomesbr commented 4 years ago

Hello folks, I've updated the SAR (https://serverlessrepo.aws.amazon.com/applications/arn:aws:serverlessrepo:us-east-1:729047367331:applications~simple-websockets-chat-app) to 1.0.3, which mirrors the latest changes in this repo.

I've also reverted the RouteSelectionExpression to $request.body.action to match the Blog post.

so now, the blog post examples should work with:

{"action": "sendmessage", "data": "message to send to other clients"}

Thanks for the continued patience on this one.

NASlR commented 4 years ago

Thanks for fixing. Could you update the readme on the repo? It's still got the old RouteSelectionExpression (which then led me to finding this issue)

dgomesbr commented 4 years ago

Done

BossLevel commented 4 years ago

To anyone who may still be having issues with this, specifically, submitting a message via a browser-based socket, rather than via wscat, the following may help. I had deployed a tweaked version of this repo and had no problem sending messages via wscat. However I had also knocked up a webpage to test sending via the browser, and whilst I could connect, any messages sent failed with the same Forbidden message. I knew there wasn't a problem with the data being sent as I could cut and paste it into wscat and it would send so it must be something else. However I did notice that in wscat, if the JSON object was malformed e.g. no double quotes, it would fail with the same error.

{ "action": "sendmessage", "data": "message" } - good { action: "sendmessage", data: "message" } - bad

In the browser JS, I was defining the message as follows:

var scktMsg = {"action":"sendmessage", "data":message}; (message being a string variable)

however I noticed when logging in the console, the object was shown as { action: "sendmessage", data: "message" } and this was failing.

I solved the problem by stringifying the object and this was then accepted by the API:

ws.send(JSON.stringify(scktMsg));

Hope this helps as it drove me up the wall for a day and a half! ;-(

fsobh commented 3 years ago

To anyone who may still be having issues with this, specifically, submitting a message via a browser-based socket, rather than via wscat, the following may help. I had deployed a tweaked version of this repo and had no problem sending messages via wscat. However I had also knocked up a webpage to test sending via the browser, and whilst I could connect, any messages sent failed with the same Forbidden message. I knew there wasn't a problem with the data being sent as I could cut and paste it into wscat and it would send so it must be something else. However I did notice that in wscat, if the JSON object was malformed e.g. no double quotes, it would fail with the same error.

{ "action": "sendmessage", "data": "message" } - good { action: "sendmessage", data: "message" } - bad

In the browser JS, I was defining the message as follows:

var scktMsg = {"action":"sendmessage", "data":message}; (message being a string variable)

however I noticed when logging in the console, the object was shown as { action: "sendmessage", data: "message" } and this was failing.

I solved the problem by stringifying the object and this was then accepted by the API:

ws.send(JSON.stringify(scktMsg));

Hope this helps as it drove me up the wall for a day and a half! ;-(

JSON.stringify fixed it for me!

tayyabgilani commented 3 years ago

@dgomesbr This is what I am doing to initiate a was connect chat from the lambda function

` const connection = new WebSocket(url);

         var test = { "message": "sendMessage", "data": "hello" };
         connection.onopen = () => {
             connection.send(JSON.stringify(test));
             console.log("connection open?????");
         };
         connection.onerror = error => {
             console.log(`WebSocket error: ${error}`);
         };
         connection.onmessage = e => {
             console.log("On message come here?????");
             console.log("EEEE", JSON.stringify(e));
             console.log(e.data);
         };`

but still having the same error { "message": "Forbidden", "connectionId": "xxxxxxxx", "requestId": "xxxxxx" }

S1rFrancis commented 3 years ago

In the connection.onopen are you subscribing to the topic. For instance when connecting to connect participant chat:

this.ws.onopen = (e) => {
      this.ws.send(
        JSON.stringify({
          topic: 'aws/subscribe',
          content: { topics: ['aws/chat'] },
        }),
      );.......