|
|
4:53 |
|
show
|
1:19 |
What's up everyone?<br>
Welcome to security, API's with FastAPI.<br>
And the Microsoft identity platform.<br>
My hope is that you're excited to learn how to build secure and robust API's using a truly fantastic Python framework like FastAPI along with modern authentication protocols such as OAUTH2 and open ID connect.<br>
FastAPI Is a Python framework for building web applications which is built on top of important fundamentals such as simplicity, performance and extensibility while making it extremely easy to learn.<br>
The Microsoft identity platform is a Federated identity provider, A system that allows you to manage and authenticate users built on top of open standards and comes with the performance, reliability and advanced capabilities.<br>
You need to quickly and easily integrate identity into your solutions.<br>
So unless you're building marketing sites with static content, it's very likely that your solution needs to know who's trying to access it and what they can do once they're in and we want to do this with as little code as possible.<br>
Therefore, I'm truly excited for this course and I look forward to learning with you.
|
|
show
|
1:19 |
Let's talk a little bit about API security.<br>
What is API security you may ask?<br>
Well API security is concerned with the confidentiality integrity and availability of your API's or CIA for short.<br>
Confidentiality is about keeping your data private and secure from unauthorized users or applications.<br>
Data should be accessed only once the appropriate permissions have been granted.<br>
Integrity on the other hand, ensures that the data is current, correct and accurate, integrity also means that the data has not been modified during transmission.<br>
And finally availability ensures that the data is available when requested via the API.<br>
Cyberattacks work across these three principles in order to compromise a system and as a fun fact, the cyber crime was measured as a country.<br>
Then in 2021 it is expected that damages inflicted by cyber attacks will total nearly $6 trillion, which would actually be the third largest economy after US and China.<br>
On this course, we will learn how to use the max of identity platform to protect confidentaility of our FastAPI.
|
|
show
|
1:01 |
Time for some introductions.<br>
My name is Christosmatskas.<br>
I work as a program manager at Microsoft, focusing on identity and security.<br>
I am also the host of the 425 show on Twitch, a twice weekly identity show.<br>
That's a lot more than just identity.<br>
I contribute to open source frequently and I love speaking at conferences and user groups whenever I can.<br>
I try to blog to share their knowledge and love about security.<br>
I Have been developing software since 2004 and therefore I had the chance to work on many different platforms, languages and tools.<br>
These days I try to help developers write better and more secure software.<br>
You can always find me on twitter @christosmatskas and you can keep track of my various activities or even reach out for help on the 425 show website aka.ms.<br>
/425Show/web.<br>
I really look forward to doing this course with you.
|
|
show
|
1:14 |
Finally, before we started looking at the specifics around API security and implementing code and if this is the first time that you're working with the FastAPI framework and Microsoft identity then there are some great resources out there that you can use to get up to speed.<br>
We'll start with a fantastic course on FastAPI.<br>
This course which is available here on talk Python does a great job introducing you to FastAPI and it takes you from the basics all the way to deploy your solution to an environment Next we jump over to the Microsoft platform where we have a developer focused course around Microsoft identity.<br>
This course covers some of the basic terminology which will also be covered here in this course.<br>
But the MS learn course goes into additional topics that are not covered here.<br>
So it's highly recommended if you're interested in identity.<br>
And finally, there is a great introduction to identity and security on Youtube where we cover some of the basic concepts to help you understand how and why identity has evolved to where we are today.<br>
Consequently, expect to see less on the implementation details and a bigger focus on the fundamentals and the history of Identity.
|
|
|
15:34 |
|
show
|
3:17 |
Before we move forward we need to understand what identity is.<br>
Identity is A set of characteristics or properties that can be used to uniquely identify a person.<br>
We all have multiple identities that are highly dependent on context at work.<br>
I'm a developer at home, I'm a dad and a husband and when I travel I'm a US citizen and so on.<br>
In the real world, proving your identity is usually pretty straightforward.<br>
You use official documents that are unique to you and can be used to prove that you are who you say you are.<br>
For example when I have to prove my age to buy alcohol at the store, I can use my driver's license or passport.<br>
The passport will be less common since we tend not to walk around or go shopping with our passports in our possession.<br>
But if I am traveling then I have to use a passport.<br>
The official documents have something in common and widely accepted authority that we all trust.<br>
A driver's license is a totally valid and acceptable form of identity within my own country And possibly when I visit other countries if I need to rent a car but it is not a valid identity document if I need to travel abroad or that when it's something that is accepted globally and carries more authority.<br>
a passport.<br>
So far so good.<br>
Now let's talk about digital identities in the digital world.<br>
We also have multiple identities and the process of proving who we say we are is far more complex.<br>
Think of all the user names and passwords.<br>
Two factor authentication apps and requirements, biometrics that you used to access your phone or other services, your Alexa, your google digital assistants and so on.<br>
Every single side out there needs to know who you are so that you can decide what you can do and it's hard to get all this right.<br>
So what makes up our digital identities?<br>
There are two distinct pieces of information that can be used to form a digital identity our digital attributes and our digital activities.<br>
Think of our digital attributes as our personally identifiable information that various organizations and companies need to store.<br>
For example when you open a new bank account or paying taxes, you need to provide different types of information that can be used to uniquely identify you Your digital activities are your online behavioral patterns, your social media interactions, your location, your browser, search history and so on.<br>
Now there is something to be said about privacy but that's for a totally different module Your digital identity is your currency on the web, everything or almost everything we do on the internet today relies on digital identities and that's why it's also a viable target for hackers.<br>
And the worst part is that we don't own our digital identities.<br>
It's the companies that we interact with that are the custodians of these identities and this is where most of the companies fall short.<br>
Every week.<br>
Another company makes the news as they fall victim to attackers that gain access to user data bases But afraid not because through this course we will learn how to build robust and secure solutions that can protect your users digital identities.
|
|
show
|
3:19 |
Our systems need to be able to store, retrieve and use digital identities in order to personalize our users experiences and secure access to sensitive information.<br>
User names and passwords have been in existence since the early days of computing we use them every day to sign into our computers, log into online banking, etc, storing and securing passwords has been a fundamental challenge for developers and security experts and an opportunity for hackers to make a lot of money.<br>
I'm pretty sure that most of you taking this course have come across one or many applications that use a user name and password database to store digital identities.<br>
And there in lies the challenge because creating a robust and secure identity system is much more than just storing a user name and password in the database.<br>
You need to cryptographically secure this information.<br>
So right from the beginning enter the wonderful world of digital cryptography but it doesn't stop there.<br>
This is only the beginning.<br>
How do you protect your system from brute force attacks?<br>
How do you protect your system from denial of service attacks?<br>
What about password resets should they be user initiated and self managed or will you have an admin to approve these requests then you have to think about two factor and multi factor authentication.<br>
Modern security requirements demand.<br>
MFA which means that you now have to integrate with multiple other services such as email, One time password tools like Authy and Microsoft authenticator and text messaging and that is more.<br>
With the prevalence of biometric capabilities in computing applications today need to be able to accommodate passwords, logins, fingerprint and face login and fighter keys.<br>
And once you solve these problems there are even more challenges such as scalability and high availability.<br>
How quickly can your database grow to accommodate new users and can you ensure that it will be available and remain available to meet the uptime requirements of your application Finally, as organizations and applications grow, how do you manage users roles, group membership permissions and so on?<br>
How extensible will your identity system be?<br>
It's also not uncommon for a company to have more than one user database lying around which creates additional challenges for admins.<br>
The lack of centralized identity system can create security holes in the infrastructure that could be used by attackers to gain unlawful access to a system.<br>
The disparity of user name and password databases creates another important problem.<br>
What happens when our digital identities need to access other resources and other systems not originally intended for building a proprietary identity system reduces interoperability and integration that can inhibit business growth Looking back at all these challenges, it feels that we are in a dire need of open standards that can be used to build a identic systems that can be easily integrated with any solution and are extensible enough to adapt to any business requirements.<br>
This is what OAUTH2 and OIDC Protocols were designed to solve and this is what we'll be looking at the next module.
|
|
show
|
3:36 |
Let's take a look at the OAUTH 2 protocol OAUTH 2 current version of OAUTH is an industry standard protocol for authorization.<br>
An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.<br>
This specification and its extensions are being developed within the IETF OAUTH working group.<br>
Okay, this doesn't say much.<br>
So let's look at how we got here and why OAUTH 2 is indispensable when building secure apps.<br>
As developers, we usually have to build systems that interact with external systems.<br>
Think of a scenario where you're building a new email client.<br>
This client needs to retrieve your users emails from gmail before OAUTH 2 the only way to do this was to ask the user for their gmail credentials.<br>
We would then use these credentials to sign into gmail as that user and retrieve the emails.<br>
If this is raising red flags, you're absolutely right as a user, this is an awful experience.<br>
You have to entrust your credentials to random up and as a developer you now have to think about how to secure the storage and retrieve these credentials.<br>
This created a lot of opportunity for abuse and security issues and believe it or not, it was the norm until OAUTH2 was created.<br>
This authorization protocol allows developers to build systems that interact with other systems without the need to touch any credentials using the same scenarios above.<br>
Instead of asking the user to provide their credentials so that our email client can get access to their gmail data.<br>
The user is instead redirected to gmail to sign in and provide the necessary consent to enable the email up power up access keys or emails upon successful authentication and authorization Gmail returns an access token back to the.<br>
email app the email client then uses this token request the necessary data and only the data that the user has consented to no calendar data, no photo data, just emails.<br>
The nice thing about this approach is that passwords are never passed around from server to server.<br>
Let's look into what a typical OAUTH2 flow looks like as well as the various components.<br>
In terms of components we have a client or application and the user.<br>
The client interacts with an authorization server and there is your server in order to authenticate and access the resource state.<br>
First the application sends an authorization request to the authorized endpoint.<br>
The authorizing point returns back an authorization grant a code.<br>
Then the application is using that authorization grant to go to the token endpoint and request an access token.<br>
Upon successful completion of that handshake the application gets back and access token.<br>
This access token allows the application to go to the resource and request access on behalf of the user.<br>
The resource validates the access token and then it turns back the secure data to the application.<br>
This is a high level simplified explanation of the OAUTH2 protocol.<br>
A way for apps to authenticate and communicate with each other without using hard coded user credentials.
|
|
show
|
2:04 |
The Oauth 2 protocols solved many problems.<br>
But as its common developers started abusing it to sign in users.<br>
Remember Oauth2 is only an authorization protocol and therefore it should only be used to request and access authorized resources, not for authenticating users.<br>
To address the shortcomings of Oauth2.<br>
The industry came up with the Open ID connect protocol or OIDC which is focused solely on user authentication.<br>
OIDC Is built on top of Oauth2 and is designed to verify a user's identity when trying to access a protected resource.<br>
That's his website or a desktop application.<br>
Open ID connect uses a similar process as Oauth in that the user is redirected away from the application to a well known identity service to sign in using either the user name and password or a social media account.<br>
The identity service returns an identity token to the application.<br>
That identity token, usually a JSON web token or JWT is used by the application to personalize the user experience and perform further authorization checks if necessary.<br>
JSON Web tokens contain vital information such as the token issuer designing time, the expiration time and user details such as name and email.<br>
This information is also called 'token claims'.<br>
In some cases, these tokens also contain additional information such as user roles or user groups that can be used by the application for authorization purposes.<br>
Many identity systems are extensible enough to allow developers to add additional claims to these tokens The important thing about the Oauth2 OIDC protocols is that application developers never have to worry about managing user credentials, since these protocols rely on an identity service to store sensitive information and only issued tokens when requested.
|
|
show
|
3:18 |
The evolution of software and hardware has brought new opportunities and new challenges.<br>
It all started with the mainframe and the dumb terminals but we quickly realized that this was not efficient or scalable.<br>
So we entered the year of personal computers, a PC or MAC on every home and every desk to paraphrase this is when client server architecture took off and the web took center stage.<br>
So enterprises spun up servers left, right and center.<br>
These servers were either on premises or hosted by a provider like Rackspace back in the day.<br>
This is what we used to build and run software Unfortunately, it soon became apparent that this was not particularly efficient because most of these servers were underutilized visualization to the rescue mutualization allowed us to squeeze even more power from our resources and this was great for a while but our industry is continuously evolving and within a few years the cloud dominated.<br>
With clouds.<br>
Our options on how to build, deploy and run software increased depending on our requirements such as cost availability, scalability etc.<br>
We can choose from infrastructural service platform as a service and software as a service.<br>
This nice little bag over here shows the difference between all these platforms using Pizza as a metaphor additional on premises are and made at home.<br>
Pizza infrastructure as a service is taking bake platform as a service.<br>
Is our pizza delivery and software as a service.<br>
Is dining out when you don't have to do anything.<br>
So you go from having full control of your pizza or your infrastructure to having no control of your pizza and your infrastructure and just ordering how you want it to look and feel and taste.<br>
Long gone are the days that we had to worry about provisioning and managing infrastructure, which is great.<br>
But not everyone out there is benefiting from the clouds.<br>
There are still many organizations that rely on traditional on premises hardware or hybrid solutions that we need to be able to cater to with such abundance of choice.<br>
Developers can now focus on building software and providing value to business.<br>
Whether you're a solo developer building a mobile application or an enterprise developer, building a web app of a major bank.<br>
The same goes for identity as we discussed earlier building and maintaining your own identity system is extremely challenging.<br>
Instead of trying to re implement the identity will.<br>
Would it not be much easier if somebody else built all that for you and all you had to do as a developer is integrated with the identity service of your choice and choice.<br>
You have, there are plenty of identity services out there.<br>
So in the end it all comes down to your criteria, cost availability, performance, platform, support, etcetera.<br>
For this course we will focus on Azure active directory, the Microsoft identity platform but we will mention if you so that you know what's out there.<br>
Okta, Auth0, PING and Sail Point are also identity service providers out there but make sure to have a look before you make final decision.
|
|
|
20:38 |
|
show
|
2:24 |
By now it should be clear that when we need to build an application that requires authenticated users or managing access to resources, we will be better off using an identity service provider.<br>
Instead of rolling our own.<br>
Identity as a service allows developers and enterprises to integrate digital identities quickly through a standard set of API's and SDK's for the purpose of this course.<br>
We will be using Azure active directory or Azure AD Azure AD is Microsoft's cloud-based identity and access management service which allows developers to authenticate users and provide access to resources.<br>
These resources can be external, such as Microsoft 365, the Azure portal and thousands of other software as a service applications Think of service now, Salesforce, Dropbox and even google apps or internal resources applications that you build or other apps in your corporate network and internet.<br>
As developers, you'll rarely have to interact with Azure Active Directory beyond setting an app registration for your apps or API's but Azure AD is capable of a lot more.<br>
At a very high level some of these features that can be used alongside your solutions to make them even more secure.<br>
Our conditional access, which is a set of policies that define who, how and when can authenticate device management to ensure that important information isn't lost in case of hardware compromise and identity protection that gives this complex machine learning and AI to monitor user behavior and prevent identity theft or loss as you can see.<br>
Azure Active directory comprises of many different components and if you were to roll out your own identity, you will have to build some of them by yourself from the ground up.<br>
But in the end there's only one thing that we, as developers care about.<br>
How easily can I implement identity into my own solution?<br>
We can break it down even further.<br>
Does my company already have an existing identity system?<br>
Does it support and integrate well with my platform and language.<br>
What kind of advanced features do I get out of the box?<br>
The answer to all of these is Azure Active Directory, which makes it straightforward to authentication and authorization using either MSAL, the Microsoft Authentication Library or any other open ID Connect and OAUTH2 libraries out there.
|
|
show
|
4:59 |
In this module, we will learn how to provision and Azure Active directory.<br>
In Azure Active Directory tenant is an instance of azure active directory.<br>
Since Azure AD is a software as a service solution.<br>
All you have to do is create one for your organization business or application.<br>
If you have a Microsoft 365 subscription or using Microsoft.<br>
Azure Microsoft cloud service, then you already have an Azure AD Tenant.<br>
However, to keep things clean and simple, we will assume that you have none.<br>
And in this module we will learn how to create Azure Active directory Tenant using Microsoft's free Microsoft 365 developer program.<br>
By registering as a Microsoft 365 developer, you get a number of services and capabilities for free.<br>
For example, you will get a fully licensed speed to Azure Active directory as well as a SharePoint online instance, Max of dynamics.<br>
As well as test accounts and data to work with and all this is free forever.<br>
And you're Microsoft 365, developer account will get renewed automatically every 90 days as long as you get to use it once within that period.<br>
So what does it take to provision and azure active directory, let's go ahead through the steps together but make sure to use your own information first navigate to aka.ms/425 Show/devenv And click the join now button or search for Microsoft 365 developer program for a better experience.<br>
I would encourage you to use a private window in your browser, click on the join now button and signing with the account.<br>
They haven't used, fill in your details, accept the terms and conditions and optionally signing for any marketing information and here you can decide what you want to use it for.<br>
I would say personal projects for now we are interested in the Microsoft identity platform We get an instant sandbox with users emails and conduct that will always get updated every day that you come in Microsoft teams and SharePoint.<br>
It will also give us 25 users to be able to test different accounts and we will press next in this last wizard.<br>
We need to create an admin account that will be used to interact with Azure active directory tenant.<br>
It's very important to store this information securely because this account has full ownership of this azure active directory tenant and you don't want to lose it when you're ready, press continue.<br>
At this point you need to use two factor authentication to validate your phone once you receive your code through sms enter it here and continue with the setup.<br>
That's the last step And with that our Microsoft 365 developer tenant has been created.<br>
What we have in front of us is the microsoft 365 developer dashboard containing some critical information such as the main name which is always useful to have.<br>
The day that our subscription expires which in this instance is May 8th 2022 and my administrator account, the owner of the tenant which I will need to use to sign into my Azure active directory.<br>
Beyond that, there's some useful information below about concepts, ideas and quick starts to help you get started with the Microsoft Identity platform.<br>
We're going to skip all this and jump straight into Azure Active directory.<br>
The easiest way to get there is by navigating to aad.portal.azure .com and then using your admin account to sign in.<br>
That's what I'm signed in.<br>
Then we'll click here we'll skip the two factors authentication for now.<br>
However, I have to highlight that it is extremely important that you set it up and for that you can use any authenticator app or the Microsoft authenticator app on your phone and yes we once they signed in and there you have it That's our Azure Active directory.<br>
Let's go through some basic information here.<br>
You notice that this is a full Azure Active directory premium with P2 license.<br>
We have all our users down here that working as part of this developer tenant, interesting fact these are actual Microsoft employees that gave permission for their names and pictures to be used when we create new testaments to help you with some sample data.<br>
Next we'll be looking at app registrations.<br>
Well done.<br>
Everyone.<br>
You now have a full azure active directory tenant to work with.
|
|
show
|
5:00 |
Before we start provisioning our very first application registration, it's important to understand what they are and why we need them.<br>
When developers need to interact with Azure Active Directory for authentication and authorization purposes, they need two things firstly, we need to create an application registration or App registration in Azure Active Directory to show our intent.<br>
This app registration is similar in most open ID connect systems if you ever had to use google or facebook to authenticate users, you know that you need to create an application.<br>
This application captures important information, such as the type of the application we're using or the type of accounts we want to authenticate, for example, organizational or external users and the open ID connect scopes, for example, the user information we want to include in our tokens as well as extra configuration settings.<br>
This application registration can be created in the portal or we can programmatically set it up using Microsoft graph API's.<br>
And this concludes the Azure Active directory configuration.<br>
Next we need to add some code in our application to initiate the signing and to handle the responses send by Azure Active Directory When working with Azure Active Directory, you can use the MSAL library which is available for most languages and frameworks out there or any other of Open ID connect library, open or closed source.<br>
Since Azure Active Directory is built on top of open standards, it uses Open ID connect certified endpoints and therefore any compatible library is acceptable.<br>
In some cases you may have to go back to Azure Active Directory to configure app registrations for Web API's.<br>
In our case we need to do that for our FastAPI.<br>
In terms of supported identities as Azure Active directory works with any work or school accounts, for example, your company's email, personal or MSA accounts like your exports account and external identities, facebook Gmail and what have you.<br>
So let's go ahead and create our very first application registration that will be used by our secure FastAPI to expose the necessary permissions to client applications and validate incoming access tokens.<br>
To the Azure AD portal.<br>
To get back to your Azure Active Directory portal type the following URL in any browser.<br>
aad.portal.azure.com.<br>
You may already have a signed in account or you may need to use your admin account to get back into the portal.<br>
In this instance I'm already signed in, I'm skipping the two factors indication and we are in under Azure Active directory.<br>
You want to find the app registration tab and here we want to create a new registration.<br>
We can name it FastAPI.<br>
We're going to leave the default accounts in this organization directory and we'll hit heads there This takes a couple of seconds.<br>
There's some important information here that we will need to use to configure our code later on this information is your application, ID your client I D, Your directory, your tenant id and your domain name, which if you can't remember how to find it.<br>
You can always go back to the overview page and this is your domain name here Back to our application registration.<br>
We need to configure one more thing to expose an api remember this is an app registration for our api, personally it said the application ID URI and this is the default name.<br>
It will give a good name but you can always override that to have a meaningful name.<br>
And with that application.<br>
ID URI .<br>
We can now go and add scopes to our api since this is for our weather api we need to create scopes that have some kind of meaning to our application.<br>
So we'll start with the weather.read permission will allow admins and users to create that and we need to give it a consent display name for that We're going to use allow users to read weather data.<br>
I tend to be lazy so I copy paste that information across the other 2 3 or four fields and we may need to make sure that it is enabled and we add the first scope.<br>
We also need to add one more scope which will be for writing data.<br>
Well, again, click the add scope, give it a weather.write permission again.<br>
Admins and Users in this instance we want to say allow users to write weather data again copy paste, there's nothing wrong with that ensure that the state is enabled and add scope and this is all it takes to configure an api app registration.<br>
Next, we will look at what it takes to create a client app registration to authenticate and test the secure FastAPI.<br>
Let's go.
|
|
show
|
8:15 |
Okay, let's pick up from where we left off.<br>
In the previous module we created an app registration inside Azure Active Directory.<br>
That will be used by our API to validate tokens and provide access and authorization to incoming requests.<br>
In this module we will look at what it takes to change our code and integrate with Azure Active directory.<br>
You could go out and write your own code but to make our lives easier, we actually provide you with a library to do that ordinarily, MSAL will be able to implement what we do.<br>
But unfortunately, the current version of MSAL Python is only able to acquire access tokens and authenticate from Azure Active Directory.<br>
It does not contain functionality to validate incoming tokens in API's.<br>
This will be coming.<br>
But in the meantime, we do have a solution.<br>
There's a package in PyPI called Fast Api Microsoft identity.<br>
That does exactly that.<br>
It's designed to validate incoming tokens against Azure Active Directory or B2C And if you remember, as you said any open ID connect and Oauth2 compatible library will be able to work with Azure Active directory.<br>
In this course we're going to build and expand on the existing source code that was provided in previous FastAPI courses.<br>
This is available on github under talk Python, Modern API's with FastAPI.<br>
We will use chapter 8 source code to add the authentication and the appropriate configuration settings to work with azure active directory.<br>
The first thing we need to do is clone the project from.<br>
Github git clone and then give it a name.<br>
That makes sense for you.<br>
I will name this fast A PI-AAD Change directory and then change directory again to chapter 8.<br>
Now we can open this project in VS Code.<br>
I like to use VS Code but you can open this project in your favorite IDE.<br>
There are a few things that we need to change to integrate our identity component into this project.<br>
We will start by creating a new settings.json file and copying the values from this template.<br>
If you followed along in the course you'll know that the main.py code expects a settings.json file and then in the requirements we need to add our Microsoft identity package We will run the restore soon remember that the necessary information to integrate with Azure Active Directory is in our app registration so let's go to our app registration.<br>
If you don't remember how to get there aad.portal.azure.com.<br>
Sign into the directory that we created as part of the previous step navigate to your App registration and copy the client ID.<br>
And the tenant ID.<br>
This information needs to go inside your settings.json ensure to save the file and that's all we have to do with settings.json.<br>
Now we can start using the FastAPI much of the identity library in our code.<br>
We'll start with main we need to import the initialize methods, you know what since our settings are inside settings.json we will pull that information and pass it into our configure off method which we will define now.<br>
This will initialize our authentication code.<br>
Let's save this.<br>
And now if we open our api weather api again we need to import the necessary components from our library.<br>
Now remember that our authentication library does two things.<br>
One is to check for an authenticated request and the second is to check for valid scopes here, we're going to define the expected scope which we should match in the access token.<br>
This needs to match what we can configure in our app registration.<br>
If we jump very quickly back into our app registration and look at the exposed api We have two scopes.<br>
A weather.write.<br>
And weather.read these are exposed by our API App registration and are expected in the access token parking our code, we expose this on line 14 with the expected scope variable.<br>
Then in our methods we need to add requires of in the method itself we need to first validate the scope, expect scope and the request object at this point you'll notice that the request object that is expected in the helper methods does not exist.<br>
So let's add it which is a request and to expose that or make it available We need to import it from the FastAPI from fastapi import request.<br>
Save this lastly we need to capture any authentication errors that may occur as the validation takes place for that.<br>
We need to add a couple more lines of code Lines 23 and 24 are responsible for capturing any errors raised during the authentication and authorization process The Fast api Microsoft identity library will capture and raise the appropriate error message with the associate http error codes.<br>
Either 401 unauthenticated or 403 unauthorized along with a meaningful error message.<br>
To help you resolve the problem in the calling client.<br>
A 401 error message will be returned if there is no valid token in the incoming request, A 403 error message will be returned.<br>
If the token is missing the appropriate scopes and permissions.<br>
For example if the user doesn't have access to this particular api and that's it.<br>
Three lines of code to implement authentication in our Api endpoint.<br>
We need to import it.<br>
We need to expose the request object.<br>
We need to add the wrapper method or the attributes and the function and then finally we need to validate the incoming scope.<br>
This will check for an authenticated request and this will make sure that the right api permissions have been acquired when calling this endpoint and if this one or this line fails then an authentication error will bubble up and send back to the user.<br>
We're going to spin up our visual environment and install all our dependencies.<br>
The one thing left now is to actually run the API.<br>
And make sure that the code is working if you're like me and you like to run and debug your code through the IDE.<br>
Especially in VS Code we can create a launch.json file.<br>
You realize that we're working with a Python application and it has some options to work with different frameworks.<br>
We can choose the FastAPI one.<br>
All we have to do is just launch the application.<br>
There is one small thing we have to change here and that is the entry point which is API which corresponds to our API object that gets initialized here and with that we can launch our application And this is great because it's now listening at port 8000 on local host which we can test, let's bring up a browser and navigate so far.<br>
So good.<br>
What will happen if we test our api endpoint which we just secured weather and you might think that this is broken, you might think that the application has failed but in fact this is an expected error This is because our request did not contain an access token in the header and therefore the API responded with a 401 in the next chapter.<br>
We'll see how we can do that using Postman or any other apytesting tools like Thunder client which I am using right now.
|
|
|
31:54 |
|
show
|
3:27 |
Welcome back everyone with our secure API.<br>
In place.<br>
It's now time to create applications.<br>
I can call it and get some data back.<br>
When it comes to working with applications there are generally two types from an identity perspective.<br>
Interactive and non interactive apps.<br>
Interactive apps.<br>
Again from an authentication perspective our applications where a user is present enable to well you know interact with the UI.<br>
In this case the authentication falls on the user.<br>
They have to provide their user name and password to authenticate and consent to an application using their data.<br>
Their information.<br>
The non interactive apps however, are usually automation programs, Headless applications or Daemon that have to use a different flow to authenticate and acquire tokens to call other API's.<br>
Or resources.<br>
Think of a console application that needs to pull some data from a secure back end perform some data transformation or queries and then upload the data back to a different system or even create a report sounds like a business of line application.<br>
Right?<br>
But another very common scenario is when you have an API.<br>
That needs to call another API.<br>
So your front end calls an API.<br>
And then that middle tier API has to call one or multiple API's.<br>
To get some data.<br>
And in that instance that API.<br>
Is acting as a headless application, there's no user interaction.<br>
These are some common scenarios where non interactive authentication needs to take place with these differences in mind there are a couple of considerations.<br>
Interactive authentication is obviously more secure since we need a user present, the user owns their credentials and the application is only there to receive a token once the authentication is successful.<br>
However, in non interactive authentication scenarios, the application itself has to know the credentials in order to sign in with the identity provider.<br>
The credentials are usually in the form of a client ID and client secret in effect, a user name and password or in the forum of a client ID.<br>
And certificate, which has to be configured both on the running system and the identity provider.<br>
Now the recommended way and best practices to use a certificate as it is much harder to steal and businesses usually have better processes for managing and renewing certificates.<br>
However, for the purpose of this course, we're only going to use client iD's.<br>
and client secrets to authenticate our non interactive applications because that keeps things simple.<br>
And another consideration is how scopes or API permissions are passed into the token with delegated permissions I where the application gets an access token for the user.<br>
The API permissions are passed as scopes in the token claims.<br>
Depending on the identity provider, the scope claim can appear as SCP or scope and the value of the claim is a space delimited string that's part of the RFC.<br>
With the application permissions on the other hand, the application requests an access token for itself and the API permissions are passed in the token as role claims.<br>
They're all claims will be an array, like collisions.<br>
Access tokens are turns into the client code and need to be passed directly to the API resource that we need to call.<br>
It's the resources responsibility to accurately pass and validate the token.<br>
Next, we will create a console application using Python to call our FastAPI get some weather data back.<br>
Let's do this.
|
|
show
|
15:19 |
In the previous module, we looked at different application types and scenarios that we can secure using Azure Active Directory.<br>
In this module will focus on a scenario where a console app written in Python can securely call our FastAPI API to many API's but you get the gist to enable our console application to authenticate and acquire an access.<br>
Talking to call our FastAPI.<br>
We need to create a new app registration in Azure Active Directory.<br>
This app registration will be our first client app.<br>
The console app is only one of the types of apps they can consume an API We could also have, for example, a web app and mobile app or even another API all calling our API.<br>
In this instance we would also have to create separate app registrations for its application type.<br>
If you're wondering why we need different app registrations per application type besides the fact that different app types require different authentication settings.<br>
The different apps also allow for segregation and better security as well as providing the ability to configure different levels of access at the application level.<br>
For example, a mobile app may be configured to allow read only access to our data, whereas a desktop client or web app could provide a more complete and rich experience with read, write access.<br>
Okay enough talking, let's switch to our Azure Active Directory and configure our app registration If you don't remember how to get to Azure Active Directory, then just type aad.portal.Azure.com.<br>
This takes you directly to one of the tenants that you may have signed in before and here was signing with the one that we created for this module, navigate to Azure active directory and from there we want the app registration tab we've done this before, remember but this time we're creating one for our console instead of an api let's create a new app registration.<br>
We'll call it console-FastAPI I will leave everything else as default.<br>
And click register next.<br>
We want to head to the authentication tab because here is where we can figure the application type and the authentication flow.<br>
So click on authentication and add a platform.<br>
The dialogue will guide you through the process.<br>
But as you can see straight away we have a mobile and desktop application web single page and what have you in this instance.<br>
We want to choose mobile and desktop applications here we should have a customary directory URI https local host and press configure we don't need to change anything else here.<br>
As we discussed in the previous module.<br>
Our console application is non interactive and therefore we need to use a client credential flow to authenticate.<br>
We already have the client ID.<br>
If we go to the overview page, you'll see that the client id's already sitting with us here.<br>
So now we need to create a new secret, navigate to the certificates and secrets tab and here you'll notice that we have the option for certificates and client secrets.<br>
To keep things simple.<br>
We will go with secrets.<br>
However it is best practice to use certificates.<br>
When you're running in production, let's create a new client secret.<br>
Give it a name, console.<br>
Secret.<br>
Change the expiry date you can say to as long as you want.<br>
I will choose three months from now and click add your secret will appear down here make sure to copy the value and not the secret ID and put it somewhere temporarily so we can use it later.<br>
It's an important thing to remember that secrets are valid for a specific period of time As with certificates, passwords do and should expire, you should automate the monitoring and the securitization for your applications to ensure that your applications remain safe and operational before you navigate away from this tab, make sure to take a note of the client's secrets and store it somewhere temporarily until we added to the application.<br>
Once you navigate away from this page, the secret is unreadable and you'll have to issue a new one.<br>
I'll put in another part for now.<br>
And don't worry I will rotate my secrets as well before I forget we need to also update our FastAPI app registration for our api to allow apps to authenticate and grab an access token.<br>
Unlike api permissions we need to configure app roles for this and you can create an app role like so give it a name, demo say applications or users and applications if you want to do so like here and then give it the permission so app.weather and give it a meaningful description and make sure to press apply.<br>
We already have that api permission here and this is what it looks like.<br>
So in effect we have everything we need inside Azure Active directory and now we can move on to write some code.<br>
Let's do this.<br>
So first things first, let me all let me open my console application and let's create a new directory for our console app.<br>
So mkdir we'll call it Python console and then we'll change directory into that and then in here now we can activate our virtual environment, Python VENV .venv.<br>
It's done.<br>
And now we also want to activate this and that's activated.<br>
Let's open this directory in code because we need to add some files.<br>
We need to add some libraries and we want to make sure that we can see what we're working with.<br>
Now you can use any editor one but my preferred editor these days is VS Code.<br>
So first we need to add the requirements.txt to store our dependencies.<br>
Next we want to create the main.py.<br>
That will contain our code.<br>
And finally, I also want to add a separate file to keep our Azure active directory configuration.<br>
So config.json.<br>
Great.<br>
Let's see what kind of dependencies we need.<br>
Well we need 2 dependencies to make our application work.<br>
One is 'msal' that's the official microsoft authentication, library package and then the other one is requests because our console application will need to craft and send the request to our Api save this one and let's switch to our config the first property when it is authority.<br>
This points to our Azure Active directory and we're going to replace common.<br>
If you were writing a multi tenant application then we could use common but since we know our directory we want to be explicit.<br>
So we will add our explicit information here.<br>
I did not close the brackett here and there you go.<br>
Then we need our client ID.<br>
Client secrets here.<br>
Make sure to copy it properly and don't miss any characters or add any characters.<br>
Otherwise it will not work.<br>
And finally we want our scope we will copy this and change it slightly with .default this setting this api scope will inform the authentication process that this is a console application and that everything has been pre consented.<br>
Remember that we pre consented data not been consent prior to this inside Azure Active directory for our scopes and that translates to the .default.<br>
The .default in effect means that when we authenticate Azure Active directory will return all the scopes that we have pre consented for if you were trying to use the previous name scope.<br>
Our authentication would fail at this point we can restore our packages or if I jump here and run pip install requirements.<br>
He should go and fetch the MSAL and request library and download them and add them to our project.<br>
And while we're here we might as well upgrade our venv whatever you prefer the pronunciation to be.<br>
And now we're good to write some code open our main.py.<br>
The first thing that we want to do is import our libraries import Json.<br>
So we can work with the config file import them msal to work with msal and the authentication and import requests.<br>
Next we want to load our json data and as you can see copilot's writing the code for me we'll soon be out of a job up will be msal.confidential client, this is confidential client application.<br>
It assumes that this application is running on a server securely and therefore we can add the credentials necessary to authenticate.<br>
The assumption is that this is secure.<br>
client_id= json data and then we have a client ID.<br>
Then we have authority which is json data authority.<br>
And then finally client credential and we have the client idea authority in client credential safe And now we want to grab our token.<br>
The standard practice with Azure Active directory is to first try to acquire a token silently in case there's a cache somewhere that the token is stored that eliminates the need to go back to Azure Active Directory and request the token but if the cache is not found or if the token is not found in the cache then we want to reach out to Azure Active directory authenticate and grab the access token.<br>
Let's write this code result = app which are confidential client acquired, token silently.<br>
Acquire token silent and then in here we're in the pass an array of scopes so you can either do this in config.json and declared the scopes as an array or we can do it in code.<br>
So here we can do json data and then open close brackets scope = none that's the first attempt and if not result therefore we don't have a token.<br>
Let's go let's reach out and get it so acquired token for clients.<br>
Remember this scope needs to be array and we do it like so at this point we assume that we have acquired a token so if access and this quote token in result then we want to print said token just to make sure that we have it correctly result access token.<br>
If not else print, result error or we can say authentication failure.<br>
That's totally up to you.<br>
Let's leave it at this.<br>
Let's run the application to see whether we can acquire a token.<br>
Very nice.<br>
I always like to grab my token and validate that it is correct And the easiest way to do this is by going to and browser typing jwt.ms or any other tool that you want to use to validate tokens and then by pasting the token up there we can see that it is the application that we requested, the token for that as our audience.<br>
That's our API.<br>
It came from the right tenant and it does include the right role.<br>
Now it doesn't, it doesn't look like a scope, it looks like a role because this is an application role or it gets it as a role but it does have the right permission and our API should read this one and translate accordingly.<br>
Remember the onus falls on the API to work with either scopes or rolls to make sure that we can retrieve our data so far so good.<br>
There's one more step now to actually call our API here and now that we have our access token.<br>
What we need to do next is we need to create a session request sessions.session and then here we need to add our header.<br>
Sessions header's update.<br>
Oh my God, look at that sessions header update.<br>
We need to add the authorization header with 'Bearer' space and our token at this point The next final step is to grab response equals session.<br>
Get Json data, not from the graph end point, Json data to get from API and remember our API is running a local host for now.<br>
Local host, I will use that auto completion to be a little more efficient.<br>
Remember it's API and then it's weather and finally we need to pass this api I'll use Seattle quotes in the brackets.<br>
I also need to remove this print statement because now we know that everything is working also we don't want to be printing out or logging our access tokens because that's private and sensitive information that somebody can steal and call your API on your behalf but we want to print the response from our session So here we'll have print response.content At this point our API is not running running this code will fail.<br>
So what we want to do is we want to run it here.<br>
We have been sitting in the waiting so let's kick this off.<br>
It's running at the expected endpoint.<br>
So if I were to run this code now we see data for Seattle if everything goes according to plan and there you have it the data is back, it does the temperature, how it feels like and other information like temperature max temperature to expect pressure and humidity that is it.<br>
We now have a console application that gets an access token and calls our api securely using the right permissions.<br>
We can quickly test whether that worked out of the box by doing something here that will break things.<br>
I always like to do that as well just to validate, we said in our API endpoint that are expected scope is app.weather.read and we have that in our token, remember if we go back to our token you'll see that's their role.<br>
So what would happen if we said our API has been configured for something else?<br>
Will this prove that we have the right information?<br>
So we're running the API again with a different permission and if we go back to our console application now and run it, we should receive an error message, bonus points.<br>
If you can think what their message would look like, it's running, it's going to fail and there you have it, this is a 403 error message.<br>
It says they're all claim does not contain the role all app.weather.read2.<br>
That's what we changed in our API or it was not found in the token.<br>
It tells us in other words that we were unauthorized to access the API, even though we had an authenticated token so that proves that end to end, we have a working solution next.<br>
We'll look on how to use a web app to call our API this time using a .net front end just to mix things up a little bit.<br>
See you in a bit.
|
|
show
|
13:08 |
In this module will go through the steps necessary to build a web app against signing users and securely call our FastAPI for the Web app we will use asp net core with .net7 .net is an open source cross platform framework by Microsoft that allows you to write code that runs everywhere.<br>
asp.net is the web component of the web framework like Django and FastAPI R for Python.<br>
However, the principles of this module should apply to any web app running on a server like java or node.js.<br>
So here we have a browser that loads or calls a web application that can call one or multiple API.<br>
And in our scenario, the web application will be calling our weather FastAPI as always.<br>
We will start with the Azure Active directory, navigate to the Azure Active directory portal via aad.portal.azure.com And go to the app registration tab.<br>
This will be under Azure Active directory.<br>
App registrations.<br>
And here we want to create a new App registration.<br>
We will name it FastAPI as web app and we'll leave everything else as default and click register at this point we might want to copy client id and tenant id as we call them.<br>
So there will be somewhere handy client Id tenant id.<br>
Always useful to have them lying around and now we want to navigate the authentication because this is how we are going to configure our web app to receive incoming tokens Once the user authenticate, we'll start with adding a platform and this time we're using web and for the redirected URI this is where the tokens will be received once the user signs in successfully.<br>
And the Azure Active directory redirect users back to the application.<br>
So this needs to match the settings in our application as well.<br>
And since its web application running on a local host .net, usually around 5001.<br>
If not, we can change it sign in OIDC.<br>
And I will show you exactly where this setting came from.<br>
Then we have access and ID tokens.<br>
So we'll press configure here.<br>
The next step is to look at certificates and secrets here.<br>
We need to configure a client's secrets if you're only planning on authenticating users in your application.<br>
This step is not necessary.<br>
However, if your web needs to get access tokens on behalf of the user, it needs to be able to authenticate against Azure Active directory that stage Why we need a client secret?<br>
Not however, that I like our console app.<br>
Example from the previous module.<br>
The users here need to consent in order to receive access tokens to our FastAPI.<br>
So let's create a new one.<br>
Let's name it web app and change it to three months and click add copy the value.<br>
Put it somewhere safe so we can use it later in case you're wondering why we don't need to configure the api permissions for FastAPI it's because the Azure Active directory allows you to have dynamic consent, which means that you can request the access token for the resources that you need to access at the time that you need them and therefore you don't have to pre configure them.<br>
That allows you to be more agile and more flexible with your app registrations as well.<br>
Now we need to create a new application through our console.<br>
.net allows you to use the cli to do so first we'll create a new directory and we will give it a meaningful name and that will change directory to the Python web.<br>
Let's clear this and now we can run the .net commands of .net new web app and -- auth single Org.<br>
What this command line will do is get a new web application and add the auth template on top of it to work with Azure Active Directory.<br>
And because we're using Azure AD and we are in a single org environment it means that we're only using one tenant to authenticate, only uses in that tenant will be able to authenticate.<br>
That's all we have to do.<br>
And this will spin up everything including all the dependencies that we need.<br>
The next step is to actually open this in code and see what we have.<br>
So here we are.<br>
The first thing that we want to do is obviously remove comments from Json.<br>
I don't know why they're there and then bring over the information that we copied it earlier.<br>
One is the way to do that is to break everything and then we'll fix it obviously but I don't want to cook, paste too many times and will add a buy in secret and add the appropriate value Remember how we said that the directory URI, should have the sign in OIDC.<br>
This is the setting here.<br>
That corresponds to that.<br>
We can always change it as long as it is the same between the Azure Active directory app registration and the settings in our code.<br>
Make sure to save this and close down.<br>
We need to update the code a little bit here.<br>
As you can see .net has made it significantly simple to add authentication and authorization in our code.<br>
In fact, it only takes one line of code but we also need to extend this now to say that we want to enable token acquisition for downstream Api's and that we also need to use a token cache.<br>
This is where the web app will store the tokens once it acquires them.<br>
And again, the nice thing about using .net with Azure Active directory is that a lot of the complexity is obstructed for us And with one line of code we can enable quite a few things.<br>
The enable token acquisition injects a token acquisition object in our code that will later use in our pages to acquire tokens.<br>
But for now this is all the code that we need to add to enable the application to sign in users and acquire access tokens.<br>
The last step in the process is to add two new files.<br>
Under pages we want to add a weather.csHTML and I will explain shortly what this means.<br>
And we also want to add one more file under pages called weather.csHTML.cs.<br>
The first file, the cs HTML file is the presentation layer.<br>
The second file is the server side code that corresponds to the web page.<br>
They're tied together.<br>
Any method and objects exposed in the code can also be accessed in the web page via the model object.<br>
When the application runs the cs HTML page is rendered to HTML So you don't see all the fluff and the code behind the scenes, we will not add too much HTML.<br>
Markup to the front end.<br>
Just a couple of lines of code that will render our weather, Json data in raw format.<br>
Obviously this is not how we would present the data in a real application but the goal here is just to show you how a web app is different to a non interactive application, like a console app.<br>
First thing that we have to do is open the weather.csHTML and add a little bit of code.<br>
First we have to start with the page directive which informs the file that this is going to be a web page And then we want to add the model.<br>
I will correspond to the code behind the CS file and then we also need to add a nice title here view data is a temporary structure that holds some information that we can pass around and here I want to say weather it's weather enough finally want to have an h3 here header or sub header that presents the data that we just pulled from the api view data and then we'll call it weather and once we populate the subject in the code behind it should be available in our HTML.<br>
This is complaining because obviously the weather model doesn't exist yet.<br>
Let's create it.<br>
We're going to be a little bit lazy here and copy a few things.<br>
So here I'm going to copy all that from the index page as the homepage of the application and then we will do some editing in the naming.<br>
So we will do hit an index model.<br>
Want to replace with weather model.<br>
Let's go very quickly through this page and see what we have.<br>
We have a weather model which is a page model and affected tells code that it is attached to the front end via this model object and we have a logger that can log some things for us every .net page gets that out of the box.<br>
We're injecting the weather model here from the middle where so can substantiate the logger don't have to create a new one every time that object gets passed via dependency injection.<br>
Finally we have an on get method.<br>
This on get method is where we implement most of the code.<br>
This function corresponds to an HTML get action when the page loads.<br>
When the browser makes a get request to the server, the code in this particular method executes and in the end we return the view I the HTML back to the user inside the on get method we need to implement two things.<br>
One is to acquire a token for API and the second is to call the FastAPI with the right headers.<br>
Now one of the things that we didn't capture from the Azure active directory portal is the permission to our API So we need to go back very quickly and grab it So from app registration the FastAPI we need the API permission for the weather.read or weather.right we'll copy one of them.<br>
We need to authorize or scope.<br>
It does expect an array or strings here.<br>
We need to add what we just copied the full thing and it is authorized for scopes and now we can add the missing name, space this in effect willforce re authentication and user consent if it hasn't been provided yet.<br>
Next we need to add our token acquisition object.<br>
I'm happy with that at this point we have the basic components of our authorization and now we need to add the token acquisition.<br>
So let's grab a token var token because yes in .net we have to say that we need to do and async because this is an efficient method but we can await it properly get access looking for user async and in here again we need to provide our scope which should be in the form of an array.<br>
The token is successfully acquired.<br>
Then the next step is to create an http client to call our FastAPI default headers request headers.authorization.<br>
I will remove that, resolve the missing name space here because I like to keep it nice and clean and we'll pass the token as a bearer token.<br>
We also want to say http client.default headers to accept add and yes we expect the media type to be Json and with that we have our http object our response and we want to call our local host 8000 because that's where our api is running.<br>
It's under API and weather type it correctly.<br>
And then the city proper ui will probably request the user to pass the name of the city so that we would pass it here dynamically.<br>
But for now we will hard code it to make sure that everything is working and now from the response we want to get a content so var content = once the content read as string async view data this is where we populate our weather object equals content.<br>
One last thing that we need to do is because I always like to run at 5000 instead of the random or that gets assigned by .net.<br>
I come in here and I change these two ports.<br>
I love and I'm Houston now there's the application.<br>
Let's see if our API is running.<br>
If not we can launch it again whether API here is not running.<br>
So let's run our FastAPI And I'm confident now that we can run and authenticate and roll our api from our web first attempt, let's see we can run it from the command line as well if we desire to do so.<br>
So here we can say .net watch, which also gives us nice recompilation.<br>
If we need to do any code changes.<br>
Okay.<br>
The application has launched it prompt us for authentication which is a good sign It means that the authentication component is working.<br>
So we're signing in the first time that we use the application and Azure Active Directory provides a consent framework which means that we need to consent for the application to access our basic profile and to get a refresh token notice also here that because I'm an admin to this azure active directory tenant.<br>
I can also concerned for everybody else and if I do that, nobody else in my organization will see this consent form.<br>
We are signed in obviously we're not seeing any weather data yet because we haven't called it.<br>
But if we navigate to the weather page, that will be presented with another consent form based on our consent framework.<br>
The first time that the application is trying to access data that we haven't consented to it will always ask for consent.<br>
This only happens once and it might never happen if your admin has already consented on behalf of your whole organization.<br>
But it notes now that we have a new one that says allow users to read weather data in our FastAPI and that's exactly what we want to do.<br>
So I'll press accept and just like that we've got our data from our fast Api not the prettiest, but it works.<br>
It's all down to you to make it presentable to summarize this chapter.<br>
We saw how non interactive and interactive applications can be configured to call our Fast Api there are small nuances between them that makes them so different yet so alike.
|
|
|
26:28 |
|
show
|
4:35 |
Authenticating a user requires the verification of the user's identity.<br>
That additional cookies based authentication method.<br>
Makes use of http cookies to authenticate client request and store session information on the server Typically the following procedure is used.<br>
A client also called, the user agent sends a login request to the server on successful login.<br>
The server stores the session information in memory or persistent storage and it sends an http response that includes an http cookie.<br>
Also called a browser cookie or web cookie in the set cookie header.<br>
A cookie is a string of data with name value pairs.<br>
As it's only required attributes.<br>
The cookie is tied with the session stored on the server and may include additional attributes for the duration of the cookie, such as how long the cookie is valid for or an expiration date.<br>
The cookie gets set in the client browser and for authentication.<br>
The client sends the cookie in the cookie header on its subsequent request.<br>
Then the server the serialize is the cookie to authenticate the user and the user remains signed in as long as cookies are stored in the browser and are valid.<br>
User specific cookie related settings can also be said in the browser by default.<br>
Most browsers expired cookie which represents a client current session.<br>
When the client shuts down the browser session, cookies based authentication has several disabilities.<br>
The session information has to be stored on the server cookies need to be sent with every request which could reduce performance especially for mobile apps.<br>
Cookies are for a specific server The main path cross origin resource setting or course http headers must be used to allow a browser to access origins such as the main scheme port other than the server zone and it is also extremely vulnerable to cross site request, forgery CSRF attacks.<br>
So what is the solution?<br>
Json web tokens which is an open Json based standard And if you want to look at the RFC then that's RFC 7519.<br>
It is designed for security transmitting information between parties.<br>
JWT or sometimes pronounced jwt is secure as it can be digitally signed using a secret with one of the supported algorithms or a public private key using RSA.<br>
In addition to secure information exchange, JWT can also be used for authentication.<br>
The following procedure is typically used for JWT based authentication.<br>
So the user logs in successfully using their credentials, user name and password or could also be Fido or can also be biometrics.<br>
The server then creates a JWT and signs it with a secret.<br>
The JWT or the signature is not stored on the server at all.<br>
The signature is created from the accorded header and the encoded payload of the JWT along with the secret and an algorithm.<br>
The JWT then is sent back to the user.<br>
The user must store the JWT securely.<br>
JWT is typically not stored in the browser which would involve the same sea surf issues as cookies do.<br>
Then the user includes the JWT token in the authorization header when accessing a security source.<br>
The server then has to verify the JWT signature as the signature is based on the information in the JWT itself.<br>
The JWT is self contained and no JWT related information is stored on the server.<br>
And if the JWT validation is successful, the server allows the user access to the requested resource.<br>
JWT based authentication has several benefits as compared to the cookies based authentication including but are not limited to stateless authentication.<br>
No user session information is stored on the server, which is great.<br>
It's not limited to specific the main paths or servers so therefore you don't suffer from the same cross origin resource sharing issues that cookies have.<br>
Json based.<br>
JWT is more compact as compared to Xml based SAML, which stands for security assertion markup language pronounced SAML.<br>
SAML is used for information exchange and it's typically used in cookies.<br>
Json is more commonly used on the internet for information exchange than xmls So libraries are more apt to working with Json.<br>
And finally, JWT can also include user permissions for specific resources using authentication and authorization platforms such as AUTH0, Azure Active Directory and so on and so on.<br>
Therefore, JWT's can also be used for authorization in addition to authentication and that's how we have ID tokens for authentication and access tokens for authorization with that information mind in the next module.<br>
We'll look in depth on how JWT's are structured and how they work.
|
|
show
|
11:24 |
In the previous module, we looked at the inherent benefits of JWT's or Json web tokens.<br>
In this module we'll look at a typical access token used by API's like our FastAPI to authorize access.<br>
There are two parties involved in an access token request the client who requests the token and the resource I the API that accepts the token when the API is called the audience claim that "aud" in a token indicates the resource.<br>
The token is intended for its audience.<br>
Clients use the token but should not understand or attempt to parse it resources accept the tokens.<br>
You can use a tool like jwt.ms to look at tokens and we've done this throughout this course, tokens consists of three parts the head, the body and the signature.<br>
Over the next few minutes we're going to dive into the individual claims so we can better understand how tokens work and what kind of information that relate to us.<br>
Let's start with the JWT header.<br>
There are three claims in the header that TIP or type, which is always a string and should always be JWT which indicates that the token is a JWT, ALG or algorithm, which is a string and indicates the algorithm used to sign the token.<br>
For example, RS 256 and finally the key ID or kid, which again is the string and specifies the thumbprint for the public key that can be used to validate this document signature.<br>
We will come back to the header and its significance in a bit.<br>
But for now let's jump to the talking body to take a look at the individual claims here, We'll start with the version which is specific to azure active directory and it is a string that indicates the version of the access token is a version one and version two.<br>
And in most cases if you're writing applications today you will be using version 2.0.<br>
ISS for issuer, which is the string and identifies the security token service.<br>
That construction is the token And the Azure AD tenant in which the user was authenticated.<br>
Your application can use the grid portion of the cling to restrict the set of tenants that can sign into the app if applicable, sub or subject.<br>
This is the string that represents the principle about which the token asserts information such as the user or an application.<br>
This value is immutable and cannot be reassigned or reused.<br>
It can be used to perform authorization checks safely, such as when the token is used to access a resource and can be used as a key in the database table because the subject is always present in the token that Azure AD issues, we recommend using this value in the general purpose authorization system.<br>
The subject is however, a pair wise identifier.<br>
It is unique to a particular application ID.<br>
Therefore, if a single user signs into two different applications using two different client id's those apps will receive two different values for the subject claim.<br>
This may or may not be desirable depending on the architecture of your solution, including the privacy requirements of your application, AUD or audience.<br>
This string identifies the intended recipient of the token its audience.<br>
Your API must validate this value and reject the token if the value does'nt match.<br>
The next three values.<br>
EXP, NBF and IAT are all integers that represent UNIX timestamps.<br>
Most authentication libraries are designed to work with UNIX timestamps so you don't have to worry about it.<br>
The EXP stands for expiration time and this claim identifies the expiration time on or after which the JWT must not be accepted for processing It's important to note that the resource may reject the token before this time as well, Such as when a change in authentication is required or a token revocation has been detected.<br>
IAT issued indicates when the authentication for this token occurred and NBF.<br>
Stands for Not Before.<br>
And this claim identifies the time before which the JWT must not be accepted for processing Name this is string and provides a human readable value that identifies the subject of the token.<br>
This value however, is not guaranteed to be unique.<br>
It is totally mutable and it is designed to be used only for display purposes.<br>
The profile scope is required in order to receive this claim.<br>
So when you request a token, you need to include the profile scope in order to receive this value back and users do and have the ability to change their name therefore, and should not be used for uniquely identifying users for the preferred user name.<br>
This again represents the user.<br>
It could be an email address or phone number or a genetic user name without the specified format.<br>
This value is also mutable and my change over time and since it is mutable, this value must not be used to make authorization decisions.<br>
OID.<br>
Or Object ID.<br>
The immutable identifier for the principle of the request the user or the service principal whose identity has been identified in ID.<br>
Tokens and app end user tokens.<br>
This is the object idea of the user and in app only tokens.<br>
This is the object ID of the calling service principle.<br>
The service principal is a cloud account.<br>
It can also be used to perform authorization checks safely as a key in database tables The identity uniquely identifies the principal across multiple applications.<br>
So unlike the subject claim, which is unique to an application inside an azure active directory, tenant.<br>
the object ID is unique to the user across multiple applications inside the same azure active directory tenants.<br>
So someone with abel.i@microsoft.com address will always have the same object ID.<br>
No matter which application they're signing into.<br>
TID or Tenant ID represents the tenant that the user is signing into.<br>
also notice that tenant id is part of the issuer claim which we covered earlier on for work and school accounts.<br>
The tid is the immutable tenant of the organization that the user signing into.<br>
For signings with the personal marks of the account tenant.<br>
For services such as Xbox themes for life or outlook.<br>
The value is always consistent is always the same.<br>
To receive this claim.<br>
Your app must request the profile scope.<br>
The nonce value is a value generated at the time that you request the access token and the value needs to be the same between the request and the response.<br>
If it isn't the same then your token has been compromised.<br>
AIO.<br>
Is an opaque claim amused by attractive director to record data for token reviews and in addition we have the SCP or scope is a space separated list of scopes.<br>
The set of scopes exposed by your application for which the client application has requested and received consent.<br>
Your app like our FastAPI should verify that these scopes are valid and make authorization decisions based on the value of the scopes roles, which is another scope that contains a list of permissions.<br>
The set of permissions exposed by your application that the requesting application or user has been given permission to call for application tokens.<br>
This is used in the client credential flow in place of user scopes and we saw that when we build our console app.<br>
However, for user tokens this is populated with the roles that the user was assigned to on the target application.<br>
Let's talk a little bit about access token and lifecycle The default lifetime for an access token is variable.<br>
When issued and access tokens default lifetime is assigned a random value between 60 and 90 minutes 75 minutes is usually the average variation improves service resiliency by spreading access talking demand over a period of 60-90 minutes which prevents hourly spikes in traffic to the identity provider.<br>
But you can also adjust the lifetime often access token to control how often your client applications expire the application session and how often it requires the user to re authenticate either silently or interactively.<br>
So what does it take to validate tokens?<br>
Well, first of all not all applications should validate tokens only in specific scenarios.<br>
Should your applications validated tokens.<br>
For web api you must validate access tokens sent by the client.<br>
They must only accept tokens that contain their audience claim or confidential Web apps like a asp core or java, you must validate ID.<br>
Tokens sent to them via the user's browser before allowing access to a user's data or establishing a session.<br>
If none of the above scenarios apply, your application will not really benefit from validating the token and may present a security and reliability risk If decisions are made based on the validity of the tokens.<br>
Public clients like native apps or single page apps don't benefit from validating tokens.<br>
The app communicates directly with the identity provider.<br>
So ssl protection ensures that the tokens are valid.<br>
api's.<br>
And web apps must only validate tokens that have an audience claim that matches their application.<br>
Other resources may have custom token validation rules.<br>
For example, tokens for Microsoft Graph one validate according to these rules due to their proprietary format validating and accepting tokens meant for another resource is an example of confused deputy problem.<br>
If your application needs to validate an ID.<br>
Token or an access token according to the above scenarios, then your app should first validate the tokens signature and issuer against the values in the open ID discovery document So validating the signature.<br>
That's where we start tokens issued by Azure Active Directory are signed using industry standard.<br>
Asymmetric encryption algorithms such as RS 256.<br>
The header of the JWT contains information about the key and encryption method used to sign the token.<br>
The ALG claim indicates the algorithm that was used to sign the token The key id claim indicates the particular public key that was used to validate the token And this is important because at any given point Microsoft can sign the token using any random set of public private key pairs and azure AD also rotates the possible set of keys on a periodic basis.<br>
So in case you're wondering how this works with your authentication code, the signing key data necessary to validate the signature using the open ID connect metadata document can be found in this URL.<br>
The important bit of information in this Json document when it comes to token validation is that jwks_uri value, which points to the set of public is used by Azure Active Directory to sign tokens at the time of sending the request the Json word keys abides to a standard format as described in RFC 7517.<br>
If you're curious to find more about it, the authentication library can use the key ID.<br>
claims in the JWT header to retrieve the public key that corresponds to the private key that has been used to sign the token.<br>
It can then do signature validation using the correct public key and the indicated algorithm.<br>
However, unless you build your own authentication library, this is not something you'll need to implement yourself or FastAPI.<br>
The FastAPI Microsoft identity library performs all these checks for you so that you focus on building the business logic for your solution.
|
|
show
|
6:23 |
In Chapter four We build a console app that used client credentials to authenticate to azure active directory.<br>
Since client credentials are nothing else than a user name and password in the form of a client id and client secret, they are inherently insecure.<br>
The recommended way to authenticate to Azure Active Directory is via certificate authentication.<br>
In this module, we will look at the steps necessary to create a self signed certificate using either open SSL or Power Shell, update the Azure Active directory app registration to use the new certificate and finally configure our app to use the certificate to authenticate and acquire an access token.<br>
While certificates are certainly more secure, self signed certificates should be avoided and only used for demos or during the development phase In production, certificates are usually managed by IT teams with strict rules and developers only consume certificates issued by an approved certificate authority.<br>
In this module.<br>
We will use openSSL However, if you are interested in using power shell then these are the commands that you would use to create a certificate.<br>
This first command would set up available to hold the certificate name.<br>
This command will generate a certificate and mark it as exportable.<br>
And if you're on Windows, this command will also install the certificate in your personal store.<br>
So it can be accessed from code the cert variable in the previous commands stores your certificate in the current session and allows you to export it export the certificate to allocation on your machine.<br>
This command exports the certificate in a CER format and you can also export it in other formats supported by Azure Active Directory including pem and cert next we need to create a password for the certificates, private key and we'll save it in variable.<br>
And finally in this last step we export the certificate in a PFX format.<br>
However, to make this accessible to everyone, we will use open ssl instead an open source cross platform tool.<br>
We're working with certificates.<br>
This command will generate an rsa.<br>
Next we need to generate a certificate request.<br>
We'll give it a name console app and the request will be console app again.<br>
The open ssl command line tool will take us through the process of setting app set and settings that are required for our certificate request here.<br>
You can enter dummy values or you can enter actual values that make sense to your project.<br>
And finally, this last command will generate the certificate for us.<br>
The duration of the certificate will be one year As the noted in days 365 will use the request that was before and we will also sign the key.<br>
The exportable value will be a PEM file.<br>
There you go.<br>
And then if we list the files in this directory now.<br>
So we have three different files, a console of CRT, the CSR and the PEM.<br>
Now that we have our certificate.<br>
We can update our Azure Active Directory app, registration accordingly.<br>
So let's head over to the portal, find your application registration, Open it up and then head over to the certificates and secrets tab select certificates and upload.<br>
Certificate browsed the location of the certificate would just create it and upload the CRT file make sure to press add and now we have a certificate uploaded here.<br>
We need to capture the thumbprint which we will use in our code and that's all we have to do inside Azure Active directory.<br>
Let's open our console app to update the code to use the certificate.<br>
The confidential client defined in the msal for Python library works with both client secrets and certificates.<br>
We saw clients secrets in action.<br>
This time we'll use certificates to authenticate.<br>
The first thing we want to do is that there are config.json instead of using a client secret, We will configure two new properties in our json file.<br>
one is our certificate And the next one is a thumbprint.<br>
Make sure to save your file before you move on to the next step and before we move on there's something that we need to discuss about these two settings here.<br>
These two bits of information are the only things needed by our confidential clients.<br>
However, if these two bits of information were to fall in their own hands then they could be used to compromise our solution.<br>
Therefore we need to take the appropriate steps to protect the certificate and the thumbprint.<br>
My recommendation would be to use a service like Azure key vault or some other service that allows you to securely offload sensitive information and moving outside the source code.<br>
If you don't have access to a service like key vault, you could install the certificate in the operating system and move the thumbprint of the thumbprint value to an environmental variable.<br>
That way our source code is still secure.<br>
However, for the purpose of this module will make them available via the config file And another thing that we need to note here is that the value of our certificate needs to be fully qualified path.<br>
In this instance the certificate is in the same location as our code.<br>
However, if you were to export and install or replace the certificate in a different location then you will need to point the allocation.<br>
You will need to use a fully qualified path.<br>
Now here in main.py.<br>
I again we want to replace this with an object that represents our certificate and this object consists of two properties in the thumbprint which we will retreive from json file.<br>
And finally we need to populate the private key by reading the contents of our certificate file there.<br>
Let's save this.<br>
I've commented out everything that has to do with a call to the Api because we just want to prove that we can acquire the token and we'll print it out here.<br>
Remember avoid printing out tokens because it is sensitive information.<br>
Let's run it successful execution as always let's validate our token using 'jwt.ms' and there we have it.<br>
We have our application authenticating successful against Azure Active Directory and acquire an access token with the appropriate roles like before But this time we're avoiding the use of client secrets and instead, we're using a certificate, which is way more secure.
|
|
show
|
4:06 |
The Oauth2 spec provides guidance on how to handle errors during authentication and authorization.<br>
Using the error portion in the error response and here is a sample response from Azure Active Directory.<br>
We can see the information that is sent to the authentication clients when they attempt to log in a user or validate a token along with recommended corrective actions Now there are a lot of errors that can be pushed out by Azure Active Directory and will go very quickly through some of them to give you an idea on what to expect and how to fix them.<br>
For example if you receive an invalid request then that means that there was a protocol error and the way to fix it is by fixing the submitted data and resubmitting the authentication request or invalid grant.<br>
You need to try a new request to the authorizing point to get a new authorization code for an unauthorized client.<br>
This usually happens when the client application isn't registered in Azure Active directory or hasn't been added to the user's Active directory.<br>
The application can prompt the user with instructions for installing the application and adding it to Azure Active Directory.<br>
This is most common in multi tenant applications.<br>
Imagine using Azure Active Directory with Adobe or Salesforce at work and using your corporate account for single sign on.<br>
So convenient if these applications have not been registered correctly by the Azure Active Directory admin then this is the error that you will see when you attempt to sign in invalid clients.<br>
The client credentials are invalid to fix the application administrator needs to update their credentials for unsupported grant type changed the grant type in the request.<br>
This type of affairs should occur only during development and should be detected during initial testing.<br>
Invalid request this indicates that the resource if it exists, has not been configured in the tenant.<br>
The application can prompt the user with instructions for installing the application and adding into the azure active directory tenant.<br>
During development this usually indicates an incorrectly setup testament or a typo in the name of the scope being requested, interaction required retry the request with the same resource interactively so that the user can complete any challenges required.<br>
And we saw this with the consent framework during our token acquisition process in previous modules.<br>
Temporarily unavailable.<br>
Retry the request in this instance the client application might explain to the user that the response is delayed because of a temporary condition.<br>
Some of these errors will be client specific whereas others will be api And back end specific.<br>
In the case of our Azure Active directory secured FastAPI A client making a request will receive a response with either 401 or 403 http status code.<br>
If an authentication or authorization error occurs.<br>
So what do these errors really mean 401 unauthorized.<br>
Although the HTTP standard specifies it as unauthorized semantically this response means unauthenticated.<br>
That is the client must authenticate itself to get the requested response.<br>
It could also mean that even though a client previously authenticated the access token in the present request has expired and therefore the client needs to re authenticate.<br>
403 forbidden A 403 error means that the client does not have access rights to the content.<br>
That is it is unauthorized.<br>
So the survey is refusing to give the requested resource.<br>
Unlike 401 unauthorized, the client's identity is known to the server.<br>
Our library will look at the scope and role claims as well as the audience claim to confirm that the authenticated client, either a user or an application has given consent to access the target resource and that the appropriate roles are present in the token.<br>
The nice thing for us securing our FastAPI with Azure Active directory is that the Microsoft library used while this courses designed to handle the authentication and authorization flow and generate the appropriate error message.<br>
All we have to do in our API is to send this back to the clients so that they can take the appropriate corrective action on their end.
|
|
|
4:49 |
|
show
|
0:34 |
Congratulations everyone.<br>
This is it.<br>
You've reached the end of the course.<br>
By now You should know what it takes to build secure scalable and production grade API's with Fast API and the Microsoft identity Platform.<br>
And you've learned how important identity security is and how straight forward it is to add authentication and authorization to your FastAPI.<br>
In order to secure access to resources in this chapter, we'll spend a bit of time maybe about a minute per module, to quickly review what we've learned and highlight the important takeaways.
|
|
show
|
0:58 |
Introduction to identity with the proliferation of the Internet.<br>
Digital identities are now everywhere.<br>
We rely on digital identities to create customizable immersive experiences while at the same time securing access to resources and sensitive information.<br>
The average person has over 1000 digital identities across the web.<br>
Identity systems are inherently hard to build as well and can easily become a target on any system.<br>
The problem is further exacerbated by the fact that most users out there are lazy and they definitely adopt bad habits when it comes to password management.<br>
With so many things that can potentially go wrong.<br>
We want to rely on a battle tested and hardened system to authenticate users and applications There are many identity providers out there that can help us build scalable and secure authentication to our applications.<br>
Microsoft identity is one self service built on top of open standards such as Open ID connect and Oauth2.
|
|
show
|
1:25 |
On module three, we looked at how we can build secure API's with Microsoft Identity.<br>
There are two parts to each authentication set up an application registration that captures the tenant to use Azure Active Directory as the authentication provider, and a bit of code to integrate with Azure Active Directory but it all starts with Azure AD Even if your organization doesn't have Azure Active Directory through Azure or Office 365 you can easily spin up your own free tenant as a developer.<br>
The only thing you need to do is usually create an application registration that contains the configurations settings necessary to set up authentication.<br>
Once your application registration is in place that only settings we need in our API.<br>
Is the client ID.<br>
and Tenant ID.<br>
Then in our API we can initialize the FastAPI Microsoft Identity library with these two settings.<br>
Usually in the bootstrap section of the API.<br>
Then for its endpoint that we want to secure, we need to declare the scope or scopes expected in the token as well as decorate our route with the requires of decorator which is part of the FastAPI Microsoft identity library.<br>
This will enforce authentication.<br>
Finally, in our function we need to validate the token against our expected scope and raising Auth error is not token valid or appropriate scopes are missing.
|
|
show
|
0:50 |
In Chapter four, we looked at how we can call our secure API.<br>
Clients that need to call our FastAPI first need to authenticate and acquire an access token.<br>
This is the standard Oauth2 process.<br>
We've also learned that depending on the application type, the authentication varies quite a bit.<br>
Interactive clients such as web apps desktop and mobile applications require a user to be present so that they can go through the overflow and consent.<br>
Non interactive applications such as daemons and api's, use a different approach.<br>
Whereas the application itself acquires a token using the client, condition flow with a secret or certificate.<br>
We also saw the different application types have different configuration settings inside Azure Active Directory and the difference between scopes and application roles and when they should be used.
|
|
show
|
0:33 |
On Chapter five, with us on advanced topics, we finally looked at the benefits of Json web tokens and why?<br>
Oauth2, is a lot more secure, both for clients and services.<br>
We took a deep dive in the anatomy of tokens and how various claims and components, such as the header can be used to check for the validity of the token and the permissions of the user or the application that acquired it and knowing how things work behind the scenes, even if we don't have to implement the token validation ourselves is critical when working with Open ID Connect and Oauth2.
|
|
show
|
0:29 |
And finally, I want to thank everyone for spending time to learn about identity and security with me.<br>
Thank you for taking my class and investing your time in my content.<br>
And huge congrats for making it all the way to the end.<br>
I truly hope that you've picked up some valuable skills to help you build some amazing API's.<br>
While keeping everyone's data safe and secure.<br>
If you want to connect with me, feel free to reach out on twitter.<br>
My handle is @christosmatskas, and I'm always happy to answer questions and with that, I really look forward to seeing you all at the next course.
|