DianaIonita / serverless-api-gateway-caching

A plugin for the Serverless framework which helps with configuring caching for API Gateway endpoints.
ISC License
136 stars 35 forks source link

[Caching with custom authorizers lambda] #87

Closed truongleeuet closed 3 years ago

truongleeuet commented 3 years ago

Please help. I have the api and I want to cache API base on roles in requestContext return from custom authorizers(picture below). Thanks

Screen Shot 2021-02-24 at 10 42 34
DianaIonita commented 3 years ago

Hi @truongleeuet,

Thanks for your question. I'm not sure you can cache requests based on the result of the authorizer. I haven't encountered anything about how one might do that. Some quick tests also show that API Gateway doesn't accept mapping expressions like method.request.requestContext.authorizer.roles. However, if your authorization is based on the value of a header, you can cache based on that value. For example, if your app sends a header like Authorization: Bearer <token>, then you can configure caching like this:

mySecureLambda:
  handler: path-to-handler/handler.handle
  events:
    - http:
        path: /the-path
        method: get
        caching:
          enabled: true
          ttlInSeconds: 3600 # caches response of lambda for 1 hour
          cacheKeyParameters:
            - name: request.header.Authorization

That means that each request should be cached based on the value of the Authorization header. If the user's role changes, you also have the option of invalidating the cache when that happens, which would mean sending a request that contains the Cache-Control: max-age=0 header along with any other cache key parameters you have configured, so API Gateway knows which key to invalidate.

Hope this helps.

DianaIonita commented 3 years ago

Closing the issue, please reopen if there are any updates.