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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video we're going to learn how to use python's fast api with azure functions and azure active directory to create secure serverless apis let's go before we get started two important dependencies that we need to talk about one is the azure function core tools or the cli tools that allow you to run and develop locally azure functions and the other one is the python runtime so if you don't have them i would urge you to download them so you can follow along in this video there are three main things that we need to do to create a secure api with fast api and azure functions firstly we need to create an azure function that we can work with locally using either the azure function core tools or vsd code secondly we need to create an azure active directory app registration that we can use to issue and validate tokens against and thirdly we need to add the necessary code components and dependencies in our function to spin up fast api handle routes and do the appropriate token validation we will do all these one step at a time okay first things first we will create a directory where our azure function will leave we can do this from the command line past api azure func then we will change directory into our newly created widgets now we can open this in vsd code with code dots let's drag this to right window and in here we can now create an azure function again i said we can use the cli or the visual code extension here create new project let's close this one we'll use the current directory we will use python and there is an important dependency here azure functions with python have a dependency on three point nine three point seven three eight or three nine if you use 310 like i was then the azure function core tools will not operate so you need to pin it to the version that is supported i39 we will use http trigger because we want to call it over http and we will give it a name secure http it will be anonymous because we don't want functions to authenticate for us we are going to use azure active directory to do the authentication authorization and with that we should get our functions project created soon you'll see it goes through the steps creates the visual environment and when this one finishes we have everything that we need to run the azure function with our browser function created we can take a quick tour to understand what all these files are doing here we will start with requirements.txt which is where we are going to place all our dependencies then we'll jump straight into our function and the init.pi is the entry point for our http based azure function currently this is what the standard template generates but we will come back and change this and finally i want to draw your attention to the vs code folder where all the configuration files leave to allow vs code to run and debug our azure function if you use vs code to generate the azure function as we did then all these files will be generated for you however if you do use the azure function core tools then you will have to manually add these files this may not be as important to you however because you may not want to use vs code to debug and you just want to run through the cli that's totally fine another nice thing about using vs code is that it went and generated visual environment for us and activated therefore we don't really have to do anything other than pressing f5 to run the function which we will do now f5 our other function is now actively listening for incoming http calls let's go and call it i like to use underclient because it's a pretty nifty tool so i will put this here and i will hold it it executed successfully it was expecting a name so let's go another name parameter and send again there you go success the first step is done we have an azure function written with python running locally and we're able to debug as well now that we know that our function runs we can jump to the azure active directory portal to configure our app registrations we will need two operations one for our api to be able to authenticate and expose api permissions one for our api to expose the api permissions and validate tokens and second for our api client to authenticate and acquire an access token for the api open the portal in the browser by navigating to aad.portal.org here we need to head out to other active directory and select app registration click on new registration give it a good name and click register the only thing that we need to do here is expose an api first set the app id uri you can change that if you want to and next we need to add the scope i will name my scope data.read i will allow admin and users to give consent and i will give a description such as read data from the api i will use copy paste to save time for the rest of the descriptions and finally i will click add scope we need to make a note of this so make sure to put it somewhere safe and we also need to capture the application or client id and the tenant id okay one down one to go back to the top level a new registration give it a meaningful name and then pass the api client and click register we have a few more steps when it comes to creating the client app sometimes when we work with apis we don't want to build a full-blown client app just to test the api in such cases we can use tools like postman which is very very popular or something else that works for you i like to use underclient which is a vs code extension it is very portable and lightweight this video is not sponsored by thunderclient but i'm open to opportunities wink wink now back to our app registration here we need to set up authentication because we need to be able to authenticate and interact with hazard active directory to sign in and get an access token we will choose accounts in this organization and add a platform we will use web now very important we need to set up the redirect uri and this comes from our thunder clients this redirect uri is in effect where azure active directory will send the access tokens back press configure and i will need a secret to be able to authenticate for that i will create a new secret i will give it a name under client leave the default of six months and create a secret please note that i will be changing this and deleting this advertising later on these secrets are sensitive information consider them as passwords and therefore they should not fall in their own hands always always protect your secrets and when possible use a certificate instead before we head out we need to capture some information we need the client id again we need a tenant id and we also need the endpoints the authorized and token endpoints they're used by thunderclan to authenticate and grab access tokens let's stop the running up and here i am going to change some settings the authorized and token urls are not going to change because i'm using the same tenant same for the callback uri but we need to add the new client id for our client we need to add the new client secrets and we also need to add the scope remember we copy that scope earlier on this is where it comes very very handy to have at this point we can actually get an access token for our api even though it's not going to be used anywhere so let's try this out make sure that we have everything correct make sure to sign in with the right account this is positive it is requiring an access document consent for our fast api so we'll press accept and if everything goes correctly coming back here we should have the new access token we can always confirm that by checking the access token in jwt.ms my name the right scope the right audience which is our api and the tenant id which is the tenant id that we're using to sign in the next and final step is to update our azure function to use fast api and the appropriate libraries to validate the incoming tokens let's do this i'm going to leave this open for now and then in here we'll start without dependencies so we need fast api and we also need fast api microsoft identity back from the command line let's restore our dependencies presence activate and then fp install requirements okay then we need to go back into our function and update most of this code first we need to add the passed api from api imports initialize our fast api and then update the code below [Music] [Music] i also want to add the context here in case we needed sweet now we also need to create a new directory where our api endpoints are going to leave at the root let's press directory let's name it this routers [Applause] and under here we need to add a new folder called weather.pie let's open weather.i import some libraries so import login which is very important from fast api we want to import router we want to import requests and we want to import response and then from our fast api microsoft library we want to import initialize we want to import requires auth auth error and validate scope we need to initialize our router and then we also want to initialize the microsoft identity library the initialize method takes two properties the tenant id which we have somewhere stored safely from the previous exercise which is a string and then we also need to pass the client id which is the identifier for our specific app registration okay we have what we need here then the next step is to create a routing endpoint oh you know what we also need an expected scope remember we talked about the scope here is the place where we want to declare that and we will say data don't read because that's what we put in our api next we need to create a new router.get we'll call it city for now and then in here we'll say requires auth we don't need the expected scope here requires auth will check for an access token in the incoming request and if one exists it will try to validate it against azure active directory if there is no token it will automatically send back a 401 response which means that the request is unauthenticated if there is a token and it is valid it will allow the rest of the process to execute and the code to execute but if there is a token that is invalid you will also get a 401 back saying that that the token is invalid could be expired for example so here we can say async def get weather i'm going to declare a request and then we want to grab the city from the incoming request i like how this works okay cool so here we want to validate the scope first we validate that there's not an active and valid access token then we validate the scope and then if we find the right data we want to return it back to the user if there is an issue what we want to do is return a response with the appropriate error message so can help the client fix the problem now there are a couple more things that we need to do before we're able to run the application first in our host.json we need to add one setting here and i will copy paste this that's for us to be able to route to the appropriate endpoint and finally in our main function we want to update this and finally in the main function we need to declare a route with the appropriate name includes router and then we'll say weather dot rooter because that's what we declared in our file and then we can add a prefix as weather and the thing that is missing here and why weather is not resolving is because we need to import it and the very last thing that we need to do is in function over here we need to update the root [Music] okay now we can try your function and see what happens and there you have it end to end security by authenticating the client acquiring an access token and calling our function and validating that the token contains the right permissions we can easily test that and make sure that we have the right permissions here by changing the expected scope and running the function again if i call the same function now we should see that we get a 403 back and as expected we do not have the right scope here and that's why it didn't work if you liked this conan and you want to see more make sure to subscribe and follow so you don't miss any updates but in essence what we created today was a secure api using azure functions python the fast api framework and the fast api microsoft library to put everything together we also did a little bit of configuration inside azure active directory to set up our authentication and api permissions you can find more details in the description below and i'll see you around
Info
Channel: Christos Matskas
Views: 17,395
Rating: undefined out of 5
Keywords: AAD, API, Authentication, Azure, Azure Ad, Azure Functions, FastAPI, Python, Serverless, authentication, authorization, azure active directory, how to repurpose content for social media, identity, lamda, learn python, learn python programming, oauth2, oidc, python basics, python course, python for beginners, python language, python programming, python programming language, python programming tutorial, python tutorial, python tutorial for beginners, security
Id: CvG1UmYSiv4
Channel Id: undefined
Length: 13min 52sec (832 seconds)
Published: Sat Apr 16 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.