This repository was archived by the owner on Nov 3, 2020. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathbasic_auth.py
More file actions
Latest commit
62 lines (51 loc) · 2.19 KB
/
Copy pathbasic_auth.py
File metadata and controls
62 lines (51 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
importbase64
importboto3
defbasicAuth(event, context):
# Return a policy which allows this user to access to this api
# this call is cached for all authenticated calls, so we need to give
# access to the whole api. This could be done by having a policyDocument
# for each available function, but I don't really care :)
arn="%s/*"%"/".join(event["methodArn"].split("/")[0:2])
# if a basic auth header is set, use that to find the correct user/token
authorizationHeader=None
if'Authorization'inevent['headers']:
authorizationHeader=event["headers"]["Authorization"]
if'authorization'inevent['headers']:
authorizationHeader=event["headers"]["authorization"]
ifauthorizationHeader:
b64_token=authorizationHeader.split(" ")[-1]
# decode the base64 encoded header value
username, token=base64.b64decode(b64_token).decode("utf-8").split(":")
# search for the given api key
client=boto3.client("apigateway")
response=client.get_api_keys(nameQuery=username, includeValues=True)
# if no keys found, deny access
iflen(response["items"]) !=1:
print("Couldn't find key")
raiseException("Unauthorized")
# if the key value does not match, deny access
ifresponse["items"][0]["value"] !=token:
print("Key value mismatch")
raiseException("Unauthorized")
# check if an x-api-token header is set, if so, take it as-is, api gateway
# will check the validity
elif"x-api-key"inevent["headers"]:
print("x-api-key received")
username="token"
token=event["headers"]["x-api-key"]
# no authentication headers found, deny
else:
print("No authentication header found")
raiseException("Unauthorized")
authResponse= {
"principalId": username,
"usageIdentifierKey": token,
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{"Action": "execute-api:Invoke", "Effect": "Allow", "Resource": arn}
],
},
}
print("Authentication response: %s"%authResponse)
returnauthResponse