Secure APIs with FastAPI and the Microsoft Identity Platform Transcripts
Chapter: JSON Web Token (JWT) Authentication
Lecture: The anatomy of JWTs and token validation

Login or purchase this course to watch this video and the rest of the course contents.
0:00 In the previous module, we looked at the inherent benefits of JWT's or Json
0:05 web tokens. In this module we'll look at a typical access token used by API's like our FastAPI to authorize access.
0:14 There are two parties involved in an access token request the client who requests the token
0:19 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.
0:29 The token is intended for its audience. Clients use the token but should not understand or attempt to parse it resources accept the
0:38 tokens. 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,
0:47 the body and the signature. Over the next few minutes we're going to dive into
0:52 the individual claims so we can better understand how tokens work and what kind of information that relate to us. Let's start with the JWT header.
1:02 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
1:11 a JWT, ALG or algorithm, which is a string and indicates the algorithm used to sign the token. For example, RS 256 and finally the key ID or kid,
1:24 which again is the string and specifies the thumbprint for the public key that can be used to validate this document signature.
1:32 We will come back to the header and its significance in a bit. But for now let's jump to the talking body to take a look at the individual
1:39 claims here, We'll start with the version which is specific to azure active directory and
1:43 it is a string that indicates the version of the access token is a version one
1:48 and version two. And in most cases if you're writing applications today you will be using version 2.0. ISS for issuer,
1:57 which is the string and identifies the security token service.
2:01 That construction is the token And the Azure AD tenant in which the user was authenticated.
2:07 Your application can use the grid portion of the cling to restrict the set of tenants that can sign into the app if applicable,
2:15 sub or subject. This is the string that represents the principle about which the token asserts information such as the user or an application.
2:23 This value is immutable and cannot be reassigned or reused. It can be used to perform authorization checks safely,
2:32 such as when the token is used to access a resource and can be used as
2:35 a key in the database table because the subject is always present in the token that
2:40 Azure AD issues, we recommend using this value in the general purpose authorization system. The subject is however, a pair wise identifier.
2:49 It is unique to a particular application ID. Therefore, if a single user signs into two different applications using two different client id's
2:57 those apps will receive two different values for the subject claim. This may or may not be desirable depending on the architecture of your solution,
3:07 including the privacy requirements of your application, AUD or audience. This string identifies the intended recipient of the token its audience.
3:15 Your API must validate this value and reject the token if the value does'nt match. The next three values.
3:21 EXP, NBF and IAT are all integers that represent UNIX
3:27 timestamps. Most authentication libraries are designed to work with UNIX timestamps so you don't have
3:32 to worry about it. The EXP stands for expiration time and this claim
3:37 identifies the expiration time on or after which the JWT must not be accepted for processing
3:43 It's important to note that the resource may reject the token before this time as
3:48 well, Such as when a change in authentication is required or a token revocation has
3:53 been detected. IAT issued indicates when the authentication for this token occurred and NBF. Stands for Not Before.
4:02 And this claim identifies the time before which the JWT must not be accepted for processing
4:08 Name this is string and provides a human readable value that identifies the subject of the token. This value however, is not guaranteed to be unique.
4:17 It is totally mutable and it is designed to be used only for display purposes. The profile scope is required in order to receive this claim.
4:25 So when you request a token, you need to include the profile scope in order to receive this value back and users
4:31 do and have the ability to change their name therefore, and should not be used for uniquely identifying users for the preferred user name.
4:39 This again represents the user. It could be an email address or phone number or a genetic user name without the specified format.
4:47 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.
4:55 OID. Or Object ID. The immutable identifier for the principle of the request the user or the service principal whose identity has been identified
5:04 in ID. Tokens and app end user tokens. This is the object idea of the user and in app only tokens.
5:11 This is the object ID of the calling service principle. The service principal is a cloud account.
5:17 It can also be used to perform authorization checks safely as a key in database tables
5:21 The identity uniquely identifies the principal across multiple applications.
5:27 So unlike the subject claim, which is unique to an application inside an azure active
5:32 directory, tenant. the object ID is unique to the user across multiple applications inside the same azure active directory tenants.
5:41 So someone with abel.i@microsoft.com address will always have the same object
5:46 ID. No matter which application they're signing into. TID or Tenant ID represents the tenant that the user is signing into.
5:55 also notice that tenant id is part of the issuer claim which we covered earlier on
6:01 for work and school accounts. The tid is the immutable tenant of the organization that
6:06 the user signing into. For signings with the personal marks of the account tenant. For services such as Xbox themes for life or outlook.
6:14 The value is always consistent is always the same. To receive this claim. Your app must request the profile scope.
6:21 The nonce value is a value generated at the time that you request the access token
6:26 and the value needs to be the same between the request and the response. If it isn't the same then your token has been compromised.
6:33 AIO. 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
6:43 list of scopes. The set of scopes exposed by your application for which the client application has requested and received consent.
6:50 Your app like our FastAPI should verify that these scopes are valid and make authorization decisions based on the value of the scopes roles,
7:00 which is another scope that contains a list of permissions.
7:03 The set of permissions exposed by your application that the requesting application or user has been given permission to call for application tokens.
7:11 This is used in the client credential flow in place of user scopes and we saw that when we build our console app.
7:17 However, for user tokens this is populated with the roles that the user was assigned
7:22 to on the target application. Let's talk a little bit about access token and lifecycle
7:27 The default lifetime for an access token is variable. When issued and access tokens default lifetime
7:35 is assigned a random value between 60 and 90 minutes 75 minutes is usually the average
7:41 variation improves service resiliency by spreading access talking demand over a period of 60-90 minutes which
7:48 prevents hourly spikes in traffic to the identity provider. But you can also adjust the lifetime often access token to control how often your client
7:57 applications expire the application session and how often it requires the user to re authenticate either
8:03 silently or interactively. So what does it take to validate tokens?
8:08 Well, first of all not all applications should validate tokens only in specific scenarios.
8:13 Should your applications validated tokens. For web api you must validate access tokens sent by the
8:19 client. They must only accept tokens that contain their audience claim or confidential Web apps like a asp core or java, you must validate ID.
8:30 Tokens sent to them via the user's browser before allowing access to a user's data or establishing a session. If none of the above scenarios apply,
8:40 your application will not really benefit from validating the token and may present a security and
8:44 reliability risk If decisions are made based on the validity of the tokens.
8:49 Public clients like native apps or single page apps don't benefit from validating tokens. The app communicates directly with the identity provider.
8:57 So ssl protection ensures that the tokens are valid. api's. And web apps must only validate tokens that have an audience
9:04 claim that matches their application. Other resources may have custom token validation rules.
9:09 For example, tokens for Microsoft Graph one validate according to these rules due to their
9:14 proprietary format validating and accepting tokens meant for another resource is an example of confused deputy
9:21 problem. If your application needs to validate an ID. Token or an access token according to the above scenarios,
9:28 then your app should first validate the tokens signature and issuer against the values in the open ID discovery document So validating the signature.
9:38 That's where we start tokens issued by Azure Active Directory are signed using industry standard. Asymmetric encryption algorithms such as RS 256.
9:47 The header of the JWT contains information about the key and encryption method used to sign
9:53 the token. The ALG claim indicates the algorithm that was used to sign the token
9:58 The key id claim indicates the particular public key that was used to validate the token
10:03 And this is important because at any given point Microsoft can sign the token using
10:09 any random set of public private key pairs and azure AD also rotates the possible set of keys on a periodic basis.
10:18 So in case you're wondering how this works with your authentication code,
10:21 the signing key data necessary to validate the signature using the open ID connect metadata document can be found in this URL.
10:30 The important bit of information in this Json document when it comes to token validation is that jwks_uri value,
10:38 which points to the set of public is used by Azure Active Directory to sign tokens
10:42 at the time of sending the request the Json word keys abides to a standard format as described in RFC 7517. If you're curious to find more about it,
10:52 the authentication library can use the key ID. claims in the JWT header to retrieve the public key that corresponds to the private
11:00 key that has been used to sign the token. It can then do signature validation using the correct public key and the indicated algorithm.
11:09 However, unless you build your own authentication library, this is not something you'll need to implement yourself or FastAPI.
11:15 The FastAPI Microsoft identity library performs all these checks for you so that you focus on building the business logic for your solution.


Talk Python's Mastodon Michael Kennedy's Mastodon