Reader small image

You're reading from  Building Data Science Applications with FastAPI - Second Edition

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632749
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron

Right arrow

Managing Authentication and Security in FastAPI

Most of the time, you don’t want everyone on the internet to have access to your API, without any restrictions on the data they can create or read. That’s why you’ll need to at least protect your application with a private token or have a proper authentication system to manage the rights given to each user. In this chapter, we’ll see how FastAPI provides security dependencies to help us retrieve credentials by following different standards that are directly integrated into the automatic documentation. We’ll also build a basic user registration and authentication system to secure our API endpoints.

Finally, we’ll cover the security challenges you must tackle when you want to call your API from a web application in a browser – in particular, the risks of CORS and CSRF attacks.

In this chapter, we’re going to cover the following main topics:

  • Security dependencies in FastAPI...

Technical requirements

For this chapter, you’ll require a Python virtual environment, just as we set up in Chapter 1, Python Development Environment Setup.

You’ll find all the code examples of this chapter in the dedicated GitHub repository at https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI-Second-Edition/tree/main/chapter07.

Security dependencies in FastAPI

To protect REST APIs, and HTTP endpoints more generally, lots of standards have been proposed. Here is a non-exhaustive list of the most common ones:

  • Basic HTTP authentication: In this scheme, user credentials (usually, an identifier such as an email address and password) are put into an HTTP header called Authorization. The value consists of the Basic keyword, followed by the user credentials encoded in Base64. This is a very simple scheme to implement but not very secure since the password appears in every request.
  • Cookies: Cookies are a useful way to store static data on the client side, usually on web browsers, that is sent in each request to the server. Typically, a cookie contains a session token that can be verified by the server and linked to a specific user.
  • Tokens in the Authorization header: Probably the most used header in a REST API context, this simply consists of sending a token in an HTTP Authorization header. The token...

Storing a user and their password securely in a database

Storing a user entity in a database is no different from storing any other entity, and you can implement this in the same way as in Chapter 6, Databases and Asynchronous ORMs. The only thing you must be extremely cautious about is password storage. You must not store the password as plain text in your database. Why? If, unfortunately, a malicious person manages to get into your database, they’ll be able to get the passwords of all your users. Since many people use the same password multiple times, the security of their accounts on other applications and websites would be seriously compromised.

To avoid a disaster like this, we can apply cryptographic hash functions to the password. The goal of those functions is to transform the password string into a hash value. This is designed to make it near impossible to retrieve the original data from the hash. Hence, even if your database is compromised, the passwords are still...

Retrieving a user and generating an access token

After successful registration, the next step is being able to log in: the user will send their credentials and receive an authentication token to access the API. In this section, we’ll implement the endpoint that allows this. Basically, we’ll get the credentials from the request payload, retrieve the user with the given email, and verify their password. If the user exists and their password is valid, we’ll generate an access token and return it in the response.

Implementing a database access token

First, let’s think about the nature of this access token. It should be a data string that uniquely identifies a user that is impossible to forge by a malicious third party. In this example, we will take a simple but reliable approach: we’ll generate a random string and store it in a dedicated table in our database, with a foreign key referring to the user.

This way, when an authenticated request arrives...

Securing endpoints with access tokens

Previously, we learned how to implement a simple dependency to protect an endpoint with a header. Here, we’ll also retrieve a token from a request header, but then, we’ll have to check the database to see whether it’s valid. If it is, we’ll return the corresponding user.

Let’s see what our dependency looks like:

app.py

async def get_current_user(    token: str = Depends(OAuth2PasswordBearer(tokenUrl="/token")),
    session: AsyncSession = Depends(get_async_session),
) -> User:
    query = select(AccessToken).where(
        AccessToken.access_token == token,
        AccessToken.expiration_date >= datetime.now(tz=timezone.utc),
    )
    result = await session.execute(query)
    access_token...

Configuring CORS and protecting against CSRF attacks

Nowadays, numerous pieces of software are designed to be used in a browser through an interface built with HTML, CSS, and JavaScript. Traditionally, web servers were responsible for handling browser requests and returning an HTML response to be shown to the user. This is a common use case for frameworks such as Django.

For a few years now, there has been a shift underway in that pattern. With the emergence of JavaScript frameworks such as Angular, React, and Vue, we tend to have a clear separation between the frontend, a highly interactive user interface powered by JavaScript, and the backend. Thus, those backends are now only responsible for data storage and retrieving and executing business logic. This is a task that REST APIs are very good at! From the JavaScript code, the user interface can then just spawn requests to your API and handle the result to present it.

However, we must still handle authentication: we want our...

Summary

That’s all for this chapter, which covered authentication and security in FastAPI. We saw that implementing a basic authentication system is quite easy thanks to the tools provided by FastAPI. We’ve shown you one way to do this, but there are plenty of other good patterns out there to tackle this challenge. However, when working on this matter, always keep security in mind and be sure that you don’t expose your application and your users’ data to dangerous threats. In particular, you’ve seen that CSRF attacks have to be taken care of when designing a REST API that will be used in a browser application. A good source to understand all the security risks involved in a web application is the OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org.

With that, we’ve covered most of the important subjects concerning FastAPI application development. In the next chapter, we’ll learn how to work with a recent technology that&...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Data Science Applications with FastAPI - Second Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781837632749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
François Voron

François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master's degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community.
Read more about François Voron