serverless / serverless/examples
Websocket authorzation handler - return something that isn't `500`?
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 11.5k
- Forks
- 4.4k
- Avg merge
- 2h 55m
- Merged PRs (30d)
- 3
Description
Question / help needed
I'm trying to get authorization working before connecting to websockets, which works, but I'm struggling to return an error message that isn't 500.
I've managed to make an auth handler, like so:
connectHandler: {
handler: 'handler.connectHandler',
events: [
{
"websocket": {
route: "$connect",
authorizer: {
name: "authHandler",
identitySource: [
// No identity source, leave it up to the handler
],
},
},
},
],
environment: {
// ..
},
},
Any my authHandler:
export const authHandler = async (event, _context) => {
console.log('🔑 Auth request received', event.requestContext)
const token = event.headers.Authorization ?? event.queryStringParameters.Authorization;
console.log('Token:', token)
if (token !== 'secret') {
return {
statusCode: 401,
}
}
return {
"principalId": "user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": event.methodArn
}
]
}
};
}
Questions:
-
what should I return in case of an error? Any request to my websocket-server that doesn't have the
secretheader/querystring returns500right now, and I'd prefer it to return a4xxstatus code. -
what is the correct type for the authorization handler? I'm using
APIGatewayProxyHandleron the other fn handlers which gives me nice inline errors.How my other handlers look like, which gives me pleasant TypeScript-errors when I do something wrong
```tsexport const connectHandler: APIGatewayProxyHandler = async (event, _context) => {
const connectionId = event.requestContext.connectionId!console.log('➕ Adding connection ', connectionId)
await client.query('INSERT INTO "public"."Connection"("id") VALUES($1) RETURNING *', [connectionId])
return {
statusCode: 200,
body: '',
};
}</details>
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the $connect websocket configuration and the authHandler return values, then compare them with the API Gateway authorizer contract and the observed 500 response. Done means the supported error status and TypeScript handler type are established for this example, with a reproducible check for requests lacking the secret.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- aws, typescript
- Domain
- api, authentication, backend
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100