Configuring Okta Authentication in FastAPI

<p>Here we are to continue our series of Okta authentication, in which we first learn about okta like how to use okta dashboard for authentication process then we use our okta domain and okta client id in react application to implement authentication on Frontend. Our can found previous articles below in Related articles section. Now, our Final Step is to configuring Okta authentication on our Backend. So, our Frontend and Backend all must be secured.</p> <h2>Prerequisites</h2> <p>Here, we specify the prerequisites for this article. It&rsquo;s assumed that the reader has a good knowledge of Python and some familiarity with FastAPI, as these skills will be essential for implementing Okta authentication in our backend.</p> <h2>Overview</h2> <p>In this section, we delve into the setup of middleware for our FastAPI application. We explain the purpose of creating a custom middleware to verify the authentication of every incoming request. We also detail the installation of the required dependency, &ldquo;okta_jwt_verifier.&rdquo;</p> <h2>Middleware Setup</h2> <p>To begin, we need to install the required dependencies for implementing Okta Authentication in FastAPI, specifically &ldquo;okta_jwt_verifier.&rdquo; You can obtain it by executing the following command:</p> <pre> pip install okta_jwt_verifier==0.2.4</pre> <p>To create a custom middleware in your&nbsp;<code>main.py</code>&nbsp;file, we will use&nbsp;<code>add_middleware()</code>. Your code will resemble the following:</p> <pre> from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .okta_middleware import OktaJWTMiddleware # Create an instance of the FastAPI class app = FastAPI() # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=&quot;*&quot;, allow_credentials=True, allow_methods=[&quot;*&quot;], allow_headers=[&quot;*&quot;], ) # Add Okta JWT Middleware app.add_middleware(OktaJWTMiddleware) # Testing URL @app.get(&quot;/&quot;) def index(): return {&quot;message&quot;: &quot;Congratulations, FastAPI this side.&quot;} # Define a route with a path parameter @app.get(&quot;/hello/{name}&quot;) async def read_item(name: str): return {&quot;message&quot;: f&quot;Hello, {name}&quot;}</pre> <h2>Custom Middleware</h2> <p>Your custom middleware, located in the&nbsp;<code>OktaJWTMiddleware</code>&nbsp;file, will look like this:</p> <pre> import os from fastapi import Request from fastapi.responses import JSONResponse from okta_jwt_verifier import JWTVerifier from starlette.middleware.base import BaseHTTPMiddleware class OktaJWTMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) async def dispatch(self, request: Request, call_next): OKTA_ISSUER = os.getenv(&quot;OKTA_ISSUER&quot;) OKTA_CLIENT_ID = os.getenv(&quot;OKTA_CLIENT_ID&quot;) accessToken = request.headers.get(&quot;authorization&quot;, None) if accessToken is not None: try: accessToken = accessToken.split(&quot; &quot;)[1] jwt_verifier = JWTVerifier(OKTA_ISSUER, OKTA_CLIENT_ID, &quot;api://default&quot;) await jwt_verifier.verify_access_token(accessToken) return await call_next(request) except Exception as e: return JSONResponse({&quot;error&quot;: f&quot;Unauthorized token or {e}&quot;}, status_code=401) else: return JSONResponse({&quot;error&quot;: &quot;Unauthorized Access&quot;}, status_code=401)</pre> <p>With this middleware in place, every request to your backend will undergo authentication. If a request is not authenticated, it will return an &ldquo;Unauthorized Access&rdquo; response.</p> <p><a href="https://ysraz.medium.com/configuring-okta-authentication-in-fastapi-c9c8c5976061">Visit Now</a></p>