Dennis Dang
06/16/2021, 6:31 AMDennis Dang
06/16/2021, 3:34 PM// Poorly documented, but API Gateway will just fail internally if
// the context type does not match this.
// Note that although non-string types will be accepted, they will be
// coerced to strings on the other side.
Dennis Dang
06/16/2021, 3:34 PMDennis Dang
06/16/2021, 4:15 PMDennis Dang
06/16/2021, 4:48 PMDennis Dang
06/16/2021, 4:48 PMFrank
// lib/ApiStack.js
import * as apigAuthorizers from "@aws-cdk/aws-apigatewayv2-authorizers";
import * as sst from "@serverless-stack/resources";
export class MainStack extends sst.Stack {
constructor(scope: <http://sst.App|sst.App>, id: string, props?: sst.StackProps) {
super(scope, id, props);
const authorizer = new apigAuthorizers.HttpLambdaAuthorizer({
authorizerName: "LambdaAuthorizer",
//responseTypes: [apigAuthorizers.HttpLambdaResponseType.SIMPLE],
handler: new sst.Function(this, "Authorizer", {
handler: "src/authorizer.main",
}),
});
const api = new sst.Api(this, "Api", {
defaultAuthorizationType: sst.ApiAuthorizationType.CUSTOM,
defaultAuthorizer: authorizer,
routes: {
"GET /": "src/lambda.main",
},
});
this.addOutputs({
Endpoint: api.url,
});
}
}
And here’s the authorizer Lambda function:
// src/authorizer.js
export const main = async (event, context, callback) => {
const authHeader = event.headers.Authorization;
let username, password;
if (authHeader) {
const base64Info = authHeader.split(' ')[1];
// Stored as 'username:password' in base64
const userInfo = new Buffer(base64Info, 'base64').toString();
[username, password] = userInfo.split(':');
}
return username === "hello" && password === "world"
? callback(null, {
principalId: '*',
policyDocument : {
Version : '2012-10-17',
Statement : [{
Action : 'execute-api:Invoke',
Effect : 'Allow',
Resource : '*',
}],
}
})
: callback('Unauthorized');
};
Dennis Dang
06/16/2021, 5:58 PM