JWT Authentication with FastAPI and AWS Cognito

Medium says I should add a picture, so here we go. Photo by Pietro Jeng on Unsplash

In this article I’ll show the following:

Background

Getting the AWS Cognito public keys

https://cognito-idp.{AWSREGION}.amazonaws.com/{POOLID}/.well-known/jwks.json

Verifying a JWT in Python

Get the correct public key

Verify the JWT

hmac_key = jwk.construct(get_hmac_key(token, jwks))

message, encoded_signature = token.rsplit(".", 1)

decoded_signature = base64url_decode(encoded_signature.encode())

return hmac_key.verify(message.encode(), decoded_signature)

Protecting FastAPI with JWT

Authorization: Bearer JWTTOKENeyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd…

Bonus: Extracting the username from the JWT

Summary

Language technology enthusiast & NLP consultant. Currently building textcloud.co, the first workflow automation platform with text intelligence.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

PHP — Combining Parallel Arrays

Lesson from zero-downtime deployments — attributing errors to specific version of code

Highlight Text with CSS

Get Soybeans Rates In Euro With An API

Best Low-cost IP Geolocation APIs In 2022

How to Fix Common SSL Issues in WordPress?

Pythonic Way Of Doing Things

An interesting tool/technology I encountered in preparation for Boot camp

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Johannes Gontrum

Johannes Gontrum

Language technology enthusiast & NLP consultant. Currently building textcloud.co, the first workflow automation platform with text intelligence.

More from Medium

Deploy your FastAPI API to AWS EC2 using Nginx

Deploy Container image on AWS lambda

Use Python logging module in AWS Lambda to send messages to CloudWatch and SNS

Migrating a WSGI Python application to Serverless on AWS