Securing Your Serverless APIs: Mastering JWT Authorization in AWS API Gateway with the Serverless Framework(Cognito)
Published: 2023-11-04 07:22:42

Authorizing API endpoints is crucial for protecting your production application from unauthorized access. By using authorizers, you can permit only authorized users to access these endpoints, bolstering security.

The traditional method of authorization involves writing middlewares that decode and verify the token sent by the client. In this process, the request first reaches the middleware, and only after successful verification, it is forwarded to the respective handlers or controllers.

In this serverless era, authorization has become more easier and can be implemented quicky. In this article, we will look at implementing jwt authorizers that verifies users from cognito pool before reaching the lamda function that handles the request. We use serverless framework to configure and deploy our lamda functions.

**Prerequisites**
AWS account
Node js installed
serverless cli configured with aws

**Create a serverless project.**

Navigate to the folder where you want to create the project and type serverless in the terminal. Create a basic node js httpApi project by choosing option from the terminal. This will create a serverless.yml file in your directory.

**Create a cognito user pool.**

In the aws management console, go to cognito and create a new userpool.

**Configure functions and events in your serverless.yaml**

```
service: your-service-name
useDotenv: true

plugins:
  - serverless-plugin-typescript
  - serverless-offline

provider:  
  name: aws
  runtime: nodejs18.x
  region: ${env:YOUR_AWS_REGION}

httpApi: 
   authorizers:
      yourAuthorizer:
        type: jwt
        identitySource: $request.header.Authorization
        issuerUrl: https://cognito-idp.${env:YOUR_AWS_REGION}.amazonaws.com/${env:YOUR_COGNITO_POOL_ID}
        audience:
          - ${env:YOUR_COGNITO_APP_CLIENT_ID}

functions:
    yourFunctionName:
    handler: handlers/authorizedFunction.httpHandler
    events:
      - httpApi:
          path: /authorizedFunction
          method: post #You can specify the method you needed here.
          authorizer:
            name: yourAuthorizer
```
**Create your lamda function**

```
function handler(event, ctx, callback) {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: "Hello from authorized function",
    }),
  };
  return response;
}

module.exports.httpHandler = handler
```

**Deploy your lamda function.**

Now deploy your lamda function by typing the command serverless in the terminal. Make sure, you have configured your aws credentials in the your system.

**Send request from the client by adding access token in the authorization headers**

```
const token = 'your-bearer-token';

const dataToSend = {
 test_data:"This is a test data"
};

const headers = {
  'Authorization': `Bearer ${token}`,
  'Content-Type': 'application/json', 
}

axios.post('your api url', dataToSend, { headers })
  .then((response) => {
    console.log('POST request successful:', response.data);
  })
  .catch((error) => {
    console.error('Error making POST request:', error);
  });
```

**Conclusion**

In the above code snippets i have used sample function and sample values. You can replace them with your real values.