Repository navigation
Expand file tree
/
Copy pathbasic_auth.py
More file actions
76 lines (57 loc) · 2.13 KB
/
Copy pathbasic_auth.py
File metadata and controls
76 lines (57 loc) · 2.13 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import base64
import json
from model.common import BasicAuthCredentials
def basic_auth_handler(event, context):
"""
This function processes the event when a certain lambda function is invoked,
specifically handling those events that includes basic auth authorizer such as api docs.
:param event: The event data.
:type event: dict
:param context: The context data.
:type context: dict
:return: The generated policy for the IAM or an unauthorized response.
:rtype: dict
"""
__ = context
authorization_header = event['authorizationToken']
auth_type, encoded_credentials = authorization_header.split(None, 1)
if auth_type != 'Basic':
return unauthorized_response('Unauthorized')
decoded_credentials = base64.b64decode(encoded_credentials).decode('utf-8')
username, password = decoded_credentials.split(':')
if username == BasicAuthCredentials.username.value and password == BasicAuthCredentials.password.value:
return generate_policy('user', 'Allow', event['methodArn'])
return unauthorized_response('Unauthorized')
def generate_policy(principal_id, effect, resource):
"""
Generates an AWS IAM policy.
:param principal_id: The principal ID.
:type principal_id: str
:param effect: The effect of the policy (e.g., 'Allow' or 'Deny').
:type effect: str
:param resource: The resource to which the policy applies.
:type resource: str
:return: The generated IAM policy.
:rtype: dict
"""
policy = {
'principalId': principal_id,
'policyDocument': {
'Version': '2012-10-17',
'Statement': [{'Action': 'execute-api:Invoke', 'Effect': effect, 'Resource': resource}],
},
}
return policy
def unauthorized_response(message):
"""
Creates an unauthorized response for HTTP requests.
:param message: The message to include in the response.
:type message: str
:return: The unauthorized response.
"""
response = {
'statusCode': 401,
'body': json.dumps({'message': message}),
'headers': {'WWW-Authenticate': 'Basic'},
}
return response