Hi everyone, could you help me? How can i import ...
# help
f
Hi everyone, could you help me? How can i import "x-api-key" for sst.Api and check in header? Anyone has example ?
Copy code
const api = new sst.Api(this, "Api", {
    routes: {
        "GET /students": "src/api/get.main",
    },
    defaultFunctionProps: {
        environment: {
            BUCKET_NAME: bucket.bucketName,
        },
        permissions: [bucket],
    }
});

this.addOutputs({
    "ApiEndpoint": api.url,
});
f
Hey @Fatih Erdinç, what do u mean by import
x-api-key
? You can get it’s value from the
event
object inside ur Lambda function.
f
@Frank Actually, I want to do basic authenticaiton for SST and I want to do this with X-Api-Key (Api Key)
r
f
If I do this configuration in serverless.yml, like that, service: comments-api provider: name: aws runtime: node14.x region: xxx profile: default apiKeys: - myapikey So how can i do that in serverless-stack?
b
As mentioned in the conversation Ross linked, you can't use API Keys with the
Api
construct as that sits above the v2 (HTTP) ApiGateway, what you want to use instead is the Rest version:
ApiGatewayV1Api
@Frank see this pop up semi-regularly, might be worth adding something to the docs on the
Api
construct page(s) that mentions the API Key support thing.
f
@Brinsley good point, will do!
@Fatih Erdinç like @Brinsley suggested, you’d need to use
ApiGatewayV1Api
in order to use the built-in API Key feature, ie.
Copy code
const api = new sst.ApiGatewayApi(...);

const plan = api.cdk.restApi.addUsagePlan('UsagePlan', {
  name: 'Easy',
  throttle: {
    rateLimit: 10,
    burstLimit: 2
  }
});

const key = api.cdk.restApi.addApiKey('ApiKey');
plan.addApiKey(key);
Let me know if this makes sense!
f
I did that
Copy code
import {HttpLambdaAuthorizer, HttpLambdaResponseType} from "@aws-cdk/aws-apigatewayv2-authorizers-alpha";

const authFunc = new sst.Function(this, "AuthorizerFn", {
    handler: "src/functions/authFunction.auth",

})

const lambdaAuthorizer = new HttpLambdaAuthorizer("Authorizer", authFunc, {
    identitySource: ["$request.header.X-Api-Key"],
    resultsCacheTtl: Duration.seconds(30),
    responseTypes: [
        HttpLambdaResponseType.SIMPLE
    ]
});
@Frank @Brinsley