Building Secure Serverless APIs with FastAPI, Azure AD, and Azure Functions using Python

Posted by


In this tutorial, we will be exploring how to create Secure Serverless APIs using Python FastAPI, Azure Active Directory (Azure AD), and Azure Functions. We will be able to authenticate users using Azure AD and secure our API endpoints.

Before we start, make sure you have an Azure account and the Azure CLI installed on your machine. Additionally, ensure you have Python and pip installed on your machine.

Step 1: Create a new Azure AD Application

  1. Sign in to the Azure portal and navigate to Azure Active Directory.
  2. Click on "App registrations" and then "New registration".
  3. Fill in the required fields and click "Register". Make note of the Application (client) ID and Directory (tenant) ID as we will need these later.
  4. Under "Certificates & secrets", create a new client secret and make note of the value.

Step 2: Set up Azure Functions

  1. Install the Azure Functions Core Tools by running the following command:
    npm install -g azure-functions-core-tools
  2. Run the following command to create a new Azure Functions project:
    func init MyFunctionProj --worker-runtime python
  3. Change into the directory of the project:
    cd MyFunctionProj
  4. Create a new HTTP-triggered function by running the following command:
    func new --name MyFunction --template "HTTP trigger" --authlevel "anonymous"

Step 3: Install FastAPI and Azure Identity

  1. Install FastAPI and uvicorn by running the following commands:
    pip install fastapi
    pip install uvicorn
  2. Install the Azure Identity library by running the following command:
    pip install azure-identity

Step 4: Create a new FastAPI application

  1. Create a new Python file called "server.py" and add the following code:
    
    from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
return {"message": "Hello World"}

2. Run the FastAPI application by running the following command:
```bash
uvicorn server:app --reload
  1. Navigate to http://localhost:8000/ in your browser to see the "Hello World" message.

Step 5: Secure the API using Azure AD

  1. Add the following code to your FastAPI application to authenticate users with Azure AD:
    
    from fastapi.security import OAuth2AuthorizationCodeBearer
    import os
    from azure.identity import DefaultAzureCredential

AZURE_CLIENT_ID = os.environ[‘AZURE_CLIENT_ID’]
AZURE_TENANT_ID = os.environ[‘AZURE_TENANT_ID’]

auth = OAuth2AuthorizationCodeBearer(authorizationUrl=f"https://login.microsoftonline.com/{AZURE_TENANT_ID}/oauth2/v2.0/authorize",
tokenUrl=f"https://login.microsoftonline.com/{AZURE_TENANT_ID}/oauth2/v2.0/token",
clientId=AZURE_CLIENT_ID)

2. Update the root endpoint to include authentication:
```python
@app.get("/")
async def root(token: str = Depends(auth)):
    return {"token": token}
  1. Add the following environment variables to your Azure Functions project:
    AZURE_CLIENT_ID=<your_client_id>
    AZURE_TENANT_ID=<your_tenant_id>
  2. Restart your FastAPI application and navigate to http://localhost:8000/ in your browser to authenticate with Azure AD.

Step 6: Deploy your Azure Function

  1. Run the following command to deploy your Azure Function:
    func azure functionapp publish <function_app_name>
  2. Once deployed, navigate to the endpoint of your Function app to see the authentication in action.

Congratulations! You have successfully created Secure Serverless APIs using Python FastAPI, Azure AD, and Azure Functions. This setup allows you to authenticate users and secure your API endpoints with Azure AD. Feel free to explore more features of FastAPI and Azure AD to enhance the security and functionality of your APIs.

0 0 votes
Article Rating

Leave a Reply

14 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@MuhammadHamid-r6o
23 days ago

you are doing great work please continue with that amazing content

@CJRomberger
23 days ago

When I hit Generate Token, absolutely nothing is happening. Haha. Dead in the water. No browser window open. Going back to the beginning of the video to see if I messed something up, or maybe something has changed? In any case, this is an awesome video for understanding the pieces of this.

@ashisharya65
23 days ago

could you please reveal the VS code theme you are using in this video?

@amarqueze
23 days ago

Great video Christos! I'm wondering if you have the plan to perform the same using Python v2 programming model. I tried to implement by myself but so far I've failed (not able to enable fastapi with microsoft AD in v2)

@patrickmurray1988
23 days ago

I have followed the instructions exactly and keep getting "Invalid_header: Unable to parse authentication" for the final API call. Any help on this?

@bn_ln
23 days ago

One great addition to this library is the get_token_claims() function. Thanks Christos!

@arashjavanmard5911
23 days ago

Great video. Thanks a lot. But I have some problems running the code:
1. azure func-tool uses system python and not the vend-python. For this, I needed to install fastapi and other stuff using system pip.
2. In weather.py-file requires_auth-function needs an "f" parameter. Otherwise, it raises type-error.

I am grateful for any support.

@josesimoes3478
23 days ago

Nice video, I'm not too familiar with Azures services so it was rather insightful

I need to give a thumbs up for the wink wink

@lacroixboi
23 days ago

you and the 425 crew put out some really awesome videos. Much appreciated!

@yashvardhan7880
23 days ago

Microsoft.AspNetCore.Routing: An error occurred while creating the route with name 'function' and template 'api//{*route}'. Microsoft.AspNetCore.Routing: The route template separator character '/' cannot appear consecutively. It must be separated by either a parameter or a literal value. (Parameter 'routeTemplate'). Microsoft.AspNetCore.Routing: The route template separator character '/' cannot appear consecutively. It must be separated by either a parameter or a literal value.

I am getting this error what should be done??

@mff5610
23 days ago

Definitely not for beginners, you have missed multiple steps and basic introductions.

@rabim8819
23 days ago

Nice one!, I like the music and the vibe.

@victormanuelagudelomedina3228
23 days ago

Do you know why ciuld have this error: ModuleNotFoundError: No module named "routers". I don't kno wwhy this can happen because I created the directory as you did and the weatehr.py as you wrote it

@thatsenpaifrommars
23 days ago

What VS code theme do you use?

14
0
Would love your thoughts, please comment.x
()
x