Last active
March 14, 2020 20:12
-
-
Save matthew-inamdar/17e2eaba44bd7ec28caabeb3b88da1af to your computer and use it in GitHub Desktop.
Implementing basic auth with the Serverless Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.handler = (evt, ctx, callback) => { | |
const authorizationHeader = evt.headers.Authorization; | |
if (!authorizationHeader) { | |
return callback("Unauthorized"); | |
} | |
const encodedCreds = authorizationHeader.split(" ")[1]; | |
const [username, password] = Buffer.from(encodedCreds, "base64") | |
.toString() | |
.split(":"); | |
if ( | |
username !== process.env.AUTH_USERNAME || | |
password !== process.env.AUTH_PASSWORD | |
) { | |
return callback("Unauthorized"); | |
} | |
callback(null, buildAllowAllPolicy(evt, username)); | |
}; | |
function buildAllowAllPolicy(evt, principalId) { | |
const tmp = evt.methodArn.split(":"); | |
const apiGatewayArnTmp = tmp[5].split("/"); | |
const awsAccountId = tmp[4]; | |
const awsRegion = tmp[3]; | |
const restApiId = apiGatewayArnTmp[0]; | |
const stage = apiGatewayArnTmp[1]; | |
const apiArn = `arn:aws:execute-api:${awsRegion}:${awsAccountId}:${restApiId}/${stage}/*/*`; | |
const policy = { | |
principalId, | |
policyDocument: { | |
Version: "2012-10-17", | |
Statement: [ | |
{ | |
Action: "execute-api:Invoke", | |
Effect: "Allow", | |
Resource: [apiArn] | |
} | |
] | |
} | |
}; | |
return policy; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
service: Website | |
provider: | |
name: aws | |
runtime: nodejs12.x | |
stage: staging | |
region: eu-west-1 | |
environment: | |
AUTH_USERNAME: admin | |
AUTH_PASSWORD: secret | |
functions: | |
website: | |
handler: index.handler | |
events: | |
- http: | |
method: any | |
path: / | |
authorizer: | |
name: basicAuth | |
resultTtlInSeconds: 0 | |
identitySource: method.request.header.Authorization | |
type: request | |
- http: | |
method: any | |
path: /{proxy+} | |
authorizer: | |
name: basicAuth | |
resultTtlInSeconds: 0 | |
identitySource: method.request.header.Authorization | |
type: request | |
basicAuth: | |
handler: auth.handler | |
resources: | |
Resources: | |
GatewayResponse: | |
Type: AWS::ApiGateway::GatewayResponse | |
Properties: | |
ResponseParameters: | |
gatewayresponse.header.WWW-Authenticate: "'Basic'" | |
ResponseType: UNAUTHORIZED | |
RestApiId: | |
Ref: ApiGatewayRestApi | |
StatusCode: '401' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment