Introduction: In this tutorial, we will build a FastAPI webpage that uses AWS Cognito for user authentication. Once the user logs in, they will see a simple chatbot page. We will walk through the code step by step and explain the main sections.
Before we start, make sure you have the following packages installed in your Python environment:
Notice that, the default pyjwt package won’t work, you might get erros such as The JWK Set did not contain any usable keys or AttributeError: module 'jwt' has no attribute 'JWTError'. It has to be the package install like this:
pip install pyjwt[crypto]
Now, let’s dive into the code.
Import necessary libraries and create a FastAPI instance:
import os import json import httpx from fastapi import FastAPI, Depends, HTTPException, status from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.security import OAuth2PasswordBearer from fastapi import Request import jwt from jwt import PyJWKClient
app = FastAPI()
Set up AWS Cognito settings:
Replace the following variables with your own AWS Cognito settings.
This endpoint is called by AWS Cognito after the user has successfully logged in. It exchanges the authorization code for an access token and redirects the user to the chatbot page. This callback url should be set up on the AWS side when you setup the app client. For test purpose, the call back url to set at aws could be “http://localhost:8000/callback". Once on production, it should be some secure url begins with https.
Reprint policy:
All articles in this blog are used except for special statements
CC BY 4.0
reprint policy. If reproduced, please indicate source
robot learner
!