Skip to content

Instantly share code, notes, and snippets.

@mglowinski93
Last active September 2, 2022 07:40
Show Gist options
  • Save mglowinski93/599736c71476e6b2558c87612068baf9 to your computer and use it in GitHub Desktop.
Save mglowinski93/599736c71476e6b2558c87612068baf9 to your computer and use it in GitHub Desktop.
Example of mocking amazon cognito
import boto3
import requests
from moto import mock_cognitoidp
def fetch_public_keys(region: str, user_pool_id: str) -> dict:
keys_url = f"https://cognito-idp.{region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json"
response = requests.get(keys_url).json()
return response["keys"]
def validate_token(token: str, keys: dict, valid_iss: str) -> dict:
"""
Steps to validate from
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
For now let's return some fake data.
"""
return {
"sub": "9cc71104-d2b8-4a84-8269-a55b95f5bd23",
"iss": "https://cognito-idp.us-west-1.amazonaws.com/us-west-1_4ujjMwsfK",
"client_id": "4pon8gi9t6f6dllka6ap2ihcad",
"origin_jti": "65e3bb61-b3ba-4156-8ebd-ae6db607310f",
"event_id": "2e63932a-3583-4265-949c-05f52bb56467",
"token_use": "access",
"auth_time": 1662022792,
"exp": 1662026392,
"iat": 1662022792,
"jti": "d5d3f3d9-c02d-41e7-a9da-4443278d61cf",
"username": "test_username",
}
@mock_cognitoidp
def test_cognito_authorization_process():
region = "us-west-1"
username = "test_username"
password = "SecurePassword1234#$%" # Password must meet security policies.
email = "test_mail@test.com"
# GIVEN
cognito_client = boto3.client("cognito-idp", region_name=region)
user_pool_id = cognito_client.create_user_pool(PoolName="TestUserPool")["UserPool"][
"Id"
]
user_pool_jwks_keys = fetch_public_keys(region=region, user_pool_id=user_pool_id)
user_pool_valid_iss = f"https://cognito-idp.us-west-1.amazonaws.com/{user_pool_id}"
app_client = cognito_client.create_user_pool_client(
UserPoolId=user_pool_id, ClientName="TestAppClient"
)
cognito_client.sign_up(
ClientId=app_client["UserPoolClient"]["ClientId"],
Username=username,
Password=password,
UserAttributes=[
{"Name": "email", "Value": email},
],
)
cognito_client.admin_confirm_sign_up(UserPoolId=user_pool_id, Username=username)
# WHEN
access_token = cognito_client.initiate_auth(
UserPoolId="AuthFlow",
ClientId=app_client["UserPoolClient"]["ClientId"],
AuthFlow="USER_PASSWORD_AUTH",
AuthParameters={"USERNAME": username, "PASSWORD": password},
)["AuthenticationResult"]["AccessToken"]
claims = validate_token(
token=access_token, keys=user_pool_jwks_keys, valid_iss=user_pool_valid_iss
)
# THEN
assert claims["username"] == username
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment