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
- Sign in to the Azure portal and navigate to Azure Active Directory.
- Click on "App registrations" and then "New registration".
- 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.
- Under "Certificates & secrets", create a new client secret and make note of the value.
Step 2: Set up Azure Functions
- Install the Azure Functions Core Tools by running the following command:
npm install -g azure-functions-core-tools
- Run the following command to create a new Azure Functions project:
func init MyFunctionProj --worker-runtime python
- Change into the directory of the project:
cd MyFunctionProj
- 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
- Install FastAPI and uvicorn by running the following commands:
pip install fastapi pip install uvicorn
- Install the Azure Identity library by running the following command:
pip install azure-identity
Step 4: Create a new FastAPI application
- 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
- Navigate to http://localhost:8000/ in your browser to see the "Hello World" message.
Step 5: Secure the API using Azure AD
- 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}
- Add the following environment variables to your Azure Functions project:
AZURE_CLIENT_ID=<your_client_id> AZURE_TENANT_ID=<your_tenant_id>
- Restart your FastAPI application and navigate to http://localhost:8000/ in your browser to authenticate with Azure AD.
Step 6: Deploy your Azure Function
- Run the following command to deploy your Azure Function:
func azure functionapp publish <function_app_name>
- 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.
you are doing great work please continue with that amazing content
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.
could you please reveal the VS code theme you are using in this video?
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)
I have followed the instructions exactly and keep getting "Invalid_header: Unable to parse authentication" for the final API call. Any help on this?
One great addition to this library is the get_token_claims() function. Thanks Christos!
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.
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
you and the 425 crew put out some really awesome videos. Much appreciated!
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??
Definitely not for beginners, you have missed multiple steps and basic introductions.
Nice one!, I like the music and the vibe.
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
What VS code theme do you use?