Safeguard your precious API endpoints built on FastAPI using OAuth 2.0
Audience Level: Beginners, Pythonistas who build on FastAPI who are not necessarily security experts but still need to deploy secure APIs.
History of OAuth 2.0? (3 mins)
- Background/history on OAuth
- Why do we need OAuth 2.0?
Authorization Challenge (2 mins)
- Why implement secure authorization now rather than later?
- Data sensitivity
OAuth 2.0 Overview (3 mins)
- Core concepts
- Key features: What are JWTs?
- Benefits of using OAuth 2.0
Technical Implementation (4 mins)
- Components of OAuth 2.0
- Different types of authorization flows and use cases
- API setup on FastAPI
Demo with FastAPI (12 mins)
- Create an endpoint in FastAPI framework and secure it with OAuth 2.0
- What are the different identity providers that can provide authorization?
- Troubleshooting common issues
Best Practices (4 mins)
- Industry-standard protocol
- Token-based security
- Should you build your authorization server?
Next Steps (2 mins)
- Ability to integrate/provide SSO with various IdPs
- Share resources to learn more including blogs, GitHub repo, etc.
- Got questions? Connect with me!
This session took place in track Security and was classified suitable for novice domain / novice python by the speaker.
Transcript (auto)
Auto-generated from the recording utilizing Open-Source AI. Speaker labels (Speaker 1, Speaker 2) reflect diarization, not identity. Timestamps refer to the recording.
Speaker 1 [00:07]
Welcome in thank you for coming to this talk on safeguard your precious API I won't repeat my chair but I'm built on fast API using OAuth so I'm assuming you're here because you want to learn about OAuth and you want to learn how to implement it on your fast API endpoints you maybe are curious about industry best practice and that's based on secure standards and And all in all, maybe your goal is to implement functional APIs, not just functional APIs, but also secure ones. So thank you for coming today. And I hope that as your guide and as your Sherpa, I can show how critical secure identity is in today's web landscape. So I learned some German from the streets of Darmstadt. So I'm going to introduce myself with something called an ID token, which is part of the extension protocol of OAuth called OpenID Connect. And what you're looking at here is an ID token. It's a JSON web token. And when it's decrypted, it has information about a user called claims. So Ich bin Simona, and I'm a developer advocate at Okta. And my scope of interests are Frisbee, board games, and Python. And as of today, eating kuchen. So where bist du? I want to know who my audience is. How many of you are web developers? Wonderful. And how many of you build with FastAPI? Oh, okay, great. And how many of you are security engineers? Okay, this is going to prove a point that I'm going to make today. But before that, let's go over the history of OAuth. So back then, companies like Twitter and Google needed a way to securely have users log in to their applications and not expose passwords. So they needed a way to standardize this. So back then, we gave companies like Yelp and maybe meetup.com our username password to be able to access our user information. So maybe giving our passwords, Gmail passwords, to be able to use our calendar, be able to access our contact list. And we've learned from our mistakes. We don't do this anymore. So OAuth, open authorization, was created as a direct response to not provide passwords anymore. And the solution was a delegated access through an identity provider. Or you can build OAuth on your own through the spec and get that access token instead of a username password to these user data. So again, OAuth solves that problem of delegated access by passing access token. So today we're having a bit of identity crisis. I work for an identity provider, and we're seeing some trends. So the trends we're seeing is that 80% of all data breaches stem from attacks on identity. And about 1.9 billion sessions have been stolen from Fortune 10,000 employees. And it takes about 290 days to recognize and contain a breach. So that's like 9 months and 16 days. And even more, we're seeing a trend in 180% as of 2003 of breaches compared to 2002. So these numbers tell a story, and they validate the need for secure identity. And the truth is, it's always been an issue. And I want to emphasize the significant risks that are involved here. This can be unauthorized access to user identities and your intellectual property, which increases the likelihood of lawsuits and lost in user trust. So therefore, prioritizing secure identity should not be a future consideration, but instead an immediate necessity to protect valuable assets and maintain credibility. So that got me to wonder, like, why is it such a hard thing to implement? Why is it an afterthought when we build web applications? And the truth is, as I've seen when I go to conferences and when I interact with developers through advocacy and through development myself, I see that we really are not security engineers, as I have asked in the audience. And so it's really out of our scope. We're building applications fast. But someone has to do it, and I can show you what is within our control. So when I mention OAuth, people think authentication, and it's not just authentication, it's also authorization. So if we were to play a game, let's say OAuth is like the base character, and it has all of these abilities that it can do, but it's limited. And then OpenID Connect is that special feature, that special extension that you can put on top of this character. You can only play it on top of this character. I don't know if you recognize this game looks like Magic the Gathering, but OAuth is maintained by the OAuth working group under the Internet Engineering Task Force. And meanwhile, OpenID Connect is maintained by the OpenID Foundation. So you can join these working groups and also contribute to the protocol. So again, OAuth is for authorization and OpenID is for authentication. it also also has different types of flows depending on your application so if you're building for web apps it has the authorization code flow for single page apps you have mobile and then for service apps you have client credential flow so if you're wondering oh can I add open ID connect to these applications you sure can you can add open ID connect on web apps so for authentication You can couple it with the authorization code flow, and then you can also do it on the authorization code flow with Pixie. But right now, OAuth 2.1 is under draft, and they are incorporating OAuth 2.0 best practices, and that OAuth 2.0 best practices mandates that we use OAuth with Pixie. And I'll show you why. But before that, I want to go through the different roles within the flows. You first have the resource owner, the client, the authorization server, and the resource server, which is a fancy way of saying the resource owner is you, the client is your application, the authorization server is the identity provider minting the access tokens, And the resource server is your API. So you can certainly build OAuth on your own. So if you're planning to do that for MCP, you can. But if you don't want that, the hassle of that, you can use an identity provider. And there are also other benefits to using an identity provider. But I recommend using Okta. And we bought Auth0. So we're outside. We have a booth. But yeah, these are all the available other IDPs. So the anatomy of an access token, this is what gets passed around for authorization into our back-end APIs. So this used to be an opaque token. It was just a string that can only be verified by the authorization server. But since the addition of OpenID Connect, It also standardized JWT tokens, so now access tokens can be JWTs, and when decrypted, it has information about users like I showed you in the beginning, and we can use that to validate locally access to resources without having to call the authorization server. So if you're building web apps, I just want to emphasize here that the front end requires that the user consents to what you're trying to access. I don't want to overcomplicate the way that the authorization code for Pixie, but just know that we're not passing around client ID, client secrets to authenticate to the back end. There's this hashing function that happens between your app and the identity provider to provide a code in exchange for a token. So web apps are private apps. It has the ability to safeguard the access token in the back end. But for SPA apps, this all happens in the front end. So there's a lot more work to make sure that your front end is secure. So today I'm going to demonstrate React front end with a fast API back end. Let me know if this is like a common tech stack for you, but I chose a modern tech stack as my example. So again, same thing. This is OAuth code with Pixie. We're not passing around secrets anymore. This is in the 2.1 best practices that will be published or published with the 2.1 version that's in draft. So we're not going to focus on the front end. We're not going to do open ID today. We're going to do back end authorization. So the benefits of using OAuth is that you can implement access tokens for an hour, and then you can renew that with a refresh token. You can have fine-grained permission and better audit capabilities if you use an IDP. And you can also revoke access tokens and refresh tokens as needed, versus API, static Like API tokens, who knows how long that lasts for? Who knows who has access to it? There's not a lot of information about that. So there's more flexibility in OAuth access tokens. So technical implementation, I did some research, and I found that FastAPI has some built-in security features. It has the HTTP bearer scheme, so we can pass the token to our endpoint and then extract it. And FastAPI will have this class that will check whether or not the token is missing. And it also has dependencies, dependency injections to make sure that for each endpoint that we We want to make sure that the access token is sufficiently scoped. We can pass on functions, too, so it's reusable. And what I did find is that there's no token verifier. So we're going to need a third party library to do that. And then it also has that cool open API documentation. So it uses type hints to build the API docs. So I'm going to use off-lib. So you see here, there's not a lot of work that I need to do. I'm using an IDP that is Okta. I'm using off-lib to help me with the decoding. And then I will demo what that looks like. So imagine us in a dungeon and we are stuck, we need to get out, there's people attacking us. How are we going to make our app secure? Are we going to roll a die? Are we going to vibe code this? Are we going to spend eternity reading the standards? I don't think so. So we're going to, I'm going to show you how to use an IDP and then with some libraries, the authlib validate the token. So the minimum claims to validate is the key that was used to sign the token, the issuer, who the token, who the token, where the token came from, and audience, the odd claim is who the token is intended for. The expiration of that token in UTC, you want to make sure that it's within plus or minus five minutes, and then optional claims are scopes. I have an app that reads messages, so I'm going to make sure that a particular scope read messages is there. And because it concerns a user, I'm going to also look for the sub, which is a subject. So there are two ways to validate a token locally, meaning we fetch the public keys that was used to sign the token from the key's endpoint. And then we, the app, will validate the token versus remote validation, which is going to the introspect endpoint and then having the authorization server validate for us. It really depends what kind of app that you're building. If you're building a more risky app like a financial or health app, you definitely want to be hitting the introspect for up-to-date information because you never know whether that user scopes have changed or that they've been let go or any changes have been made. So, there's also this really cool authorization server discovery URL, and this pretty much tells us public information about all the end points where the client can go to ask for the key signatures and where to ask for tokens and where to authorize and such things like that. So I'm running my react front end. So when I log in, I'm redirected to Okta, and this is where I'm going to authenticate. And I haven't authenticated for a while. So this is me copying my password, but try to forget it as soon as you see it. But that's okay if you have my password, because Okto will ask for another authenticator, and that is my finger, and I don't know how you're going to get my finger. Then I'll go to this profile page, and here you'll see my ID token claims, similar to how I presented myself. I have information about myself through the ID claim. And then I want to hit the messages endpoint, and here it is. You are free from the dungeon. But how did I do that? Let's go back to the code. Put this up here. So from, let's see, FastAPI security module, I got the HTTP bearer. And I also had a course policy, which is making sure that I get the request from the front end through a particular domain and not just any domain. I have the introspect as a Boolean. So when I turn it on, I could be able to use that. Let's see. But now what I did was a local validation. And under the verify underscore token function, I have here checking the keys. So from the authlib, I'm using the jot.decode function. And that allows me to get the key, get the token, and make sure that the expiration claim is within the claims option. I really need that to be there, so I made that an essential option there. So then I check for the audience, I check for the issuer, I check for the expiration date, and then the scopes. And so up here, I've listed that the scopes that must be there is read messages. And I was lucky to find Offlib also has some cool error handling so it was all there so there's not much I did I use an IDP I use the off-lib and yeah let's get back to so these is just screenshots for if I wasn't able to show you live but so again troubleshooting common issues make Make sure that your token storage is secure. Don't have overly permissive scopes, so least privilege. Make sure you have the minimum validation that I talked about. And then have some error handlings in there as well. So when you're choosing a library, make sure that it's maintained and current. Don't just choose any library. a boon if it's certified by OIDC OAuth, but yeah, should you be building your own authorization server? No, if you can help it, use an IDP, that's what they're there for. You can check out the RFC 9700 for best practices on OAuth 2.0 security. Make sure you have some rate limiting to see if there's any brute force attack. You want thoughtful scope design. I name mine read messages. So make sure you have a library of the different scopes that you're going to share with your team. What else? So yeah, I really hope I streamlined this for you and really emphasized the need for secure identity. I have more information, a list of curated information for you to check out. This is based on current best practices, again, and me coming from Okta, we really are seeing the trends and what really needs to be implemented, especially in the enterprise. So if you're planning to sell to the enterprise, there are things that you need to have in in your application that they're going to be looking for. And because this is AI related for the model context protocol, what does MCP think about OAuth? It loves it. It really is, if you can see the client is making a request outside of the environment. So to be able to make external calls for API services to make external calls, you can use OAuth. And the way to do that is to implement Pixie. But if you don't want to do it yourself, an IDP is the way to go. So we're going to redirect to an IDP to consent the user for the client what it is authorized to do. So exactly like that app, giving that consent, that is the way to go or the future of MCP authentication authorization. So I have more information on that if you want to talk about that. Feelin' dunk. And yeah, if you have any questions about MCP or authorizing, authenticating your Gen AI, come see me at the Auth0 booth. I also have some swag. I have some beanies, and I have stickers and YubiKeys. So if you're interested in that, come see me.
Speaker 2 [24:00]
Thank you very much for the insightful talk. And I have to thank the audience being really well-behaving. No one kicked a bottle for a whole 30 minutes. Never happened before. So this shows the focus. So I have some questions for you from the audience. You can still submit your questions on Slido. You know the drill. So the first one, can we still trust the logins coming from Meta, Google, et cetera? Is it trustable by itself or can there be misuse from these providers?
Speaker 1 [24:35]
So, yeah, we, well, Google has a high stake on OAuth and OpenID Connect. So, they definitely contribute to the standardization. So, they're definitely trusted. Well, yeah, clean. So, yeah, we can use social IDPs. Yes, and as long as they implement the standards that we abide by, they can certainly be used.
Speaker 2 [25:12]
The next one what about the network traffic any bottlenecks for an app with huge amount of requests
Speaker 1 [25:21]
Oh, do you mean to one endpoint, or? A request. Is this a networking issue?
Speaker 2 [25:30]
You can look from different perspectives as you see it.
Speaker 1 [25:35]
So if that's logging in, I don't know, I don't really know, I don't really understand the question, but if it's like logging into from an IP or is that a secure issue?
Speaker 2 [25:51]
that the question? In terms of traffic, I don't know.
Speaker 1 [25:55]
I'm sorry next
Speaker 2 [25:59]
Can this be provided as a middleware to FAST API?
Speaker 1 [26:04]
So, Authlib is what I'm suggesting is the middleware. So, for OIDC, there is some functions you can use to redirect to Okta. But what I used, what was used for my front end was an Okta-based SDK. So, you can certainly use Authlib, but you can also use Okta SDKs. Yeah, as middleware, yeah.
Speaker 2 [26:37]
The last question submitted from the audience is, which auth library is good? Why did you choose Authlib?
Speaker 1 [26:44]
So, I chose it because it's sponsored by Auth0, so we use it. And also, I mentioned that it must be maintained and current. So if it's also certified by OIDC and OAuth, that's a plus. So be sure to be looking out whether or not they follow the secure standards. And, yeah.
Speaker 2 [27:12]
Then I ask my own question, okay. What makes you love your job? Because it was obvious to see your passion and enthusiasm as a developer advocate. What is the best part of it?
Speaker 1 [27:24]
I think it was shocking for me to hear that web developers need to be concerned with security as well. So when I graduated from a boot camp in San Francisco, we were not taught security. So we were taught, oh, just create this full stack app and you're done, right? But they didn't teach us at all about security. security. So now that I'm in the realm of identity providers, I see very much how it's important. So I want to tell everybody that it's so. I proposed this talk to the PyCon community, and I'm so happy that people feel the same and that it's such an important topic to talk about. And we're not But yeah, we're not taught at school, or we have to figure this out on our own. And it's a very sensitive topic.
Speaker 2 [28:22]
Thanks again for coming over with Hoodies Goodies.
Speaker 1 [28:25]
Goodies, goodies, goodies and goodies.
Speaker 2 [28:27]
Yeah. Thanks, everyone.
Speaker 1 [28:29]
Yeah, so if you have any questions on architecture, we can talk about it at the booth. Yeah.