https://serverless-stack.com/ logo
#help
Title
# help
f

Fatih Erdinç

04/23/2022, 3:44 PM
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

Frank

04/23/2022, 3:48 PM
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

Fatih Erdinç

04/23/2022, 3:57 PM
@Frank Actually, I want to do basic authenticaiton for SST and I want to do this with X-Api-Key (Api Key)
r

Ross Coundon

04/23/2022, 4:05 PM
f

Fatih Erdinç

04/23/2022, 4:11 PM
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

Brinsley

04/25/2022, 7:18 AM
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

Frank

04/27/2022, 11:44 PM
@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

Fatih Erdinç

04/29/2022, 12:24 PM
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