new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

advanced-dependencies/security

29 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

HTTP Basic Auth overview

HTTP Basic Auth expects a header containing username and password. If not received, the application returns HTTP 401 'Unauthorized' with a WWW-Authenticate header containing 'Basic' and optional realm parameter. This tells the browser to show an integrated prompt for username and password, which the browser then sends automatically in headers.

HTTPBasic security scheme setup

To implement HTTP Basic Auth in FastAPI: import HTTPBasic and HTTPBasicCredentials, create a security scheme using HTTPBasic(), and use that security object with a dependency in a path operation. It returns an HTTPBasicCredentials object containing the username and password sent by the client.

Validate HTTP Basic Auth credentials securely

Use the Python standard library secrets module with secrets.compare_digest() to validate credentials. Since secrets.compare_digest() requires bytes or ASCII-only strings, convert username and password to bytes using UTF-8 encoding first. This approach prevents timing attacks.

Timing attacks explained

A timing attack exploits the fact that string comparison returns False as soon as the first character differs, which is faster than comparing identical strings character-by-character. Attackers can measure response time to determine which characters are correct, gradually guessing credentials. With thousands or millions of attempts per second, attackers can deduce the correct username and password by observing microsecond differences in response time.

secrets.compare_digest() prevents timing attacks

secrets.compare_digest() takes the same amount of time to compare two different strings regardless of which characters differ or where the difference occurs. This eliminates the timing information attackers would use to gradually deduce correct credentials.

Return HTTP Basic Auth rejection

When HTTP Basic Auth credentials are detected as incorrect, return an HTTPException with status code 401 and include the WWW-Authenticate header to trigger the browser to show the login prompt again.

Advanced security features beyond tutorial basics

FastAPI provides extra features to handle security beyond what is covered in the Tutorial - User Guide: Security. These sections are not necessarily "advanced" and the solution for many use cases may be found in them.

Advanced security sections build on tutorial concepts

The advanced security sections assume you have already read the main Tutorial - User Guide: Security. They are all based on the same concepts but allow some extra functionalities.

OAuth2 scopes parameter format

OAuth2 scopes are defined in the specification as a list of strings separated by spaces. Each scope is a string without spaces that represents a specific permission. Examples include 'users:read', 'users:write', 'instagram_basic', or 'https://www.googleapis.com/auth/drive'. The content format can vary but must not contain spaces.

Security scheme with scopes parameter

When declaring an OAuth2 security scheme in FastAPI, use the 'scopes' parameter which receives a dict with each scope as a key and the description as the value. This makes the scopes appear in the API docs when users log in or authorize.

Import and use Security for scope declaration

Import 'Security' from 'fastapi' to declare dependencies with scope requirements. Use 'Security' instead of 'Depends' when you need to specify security scopes. Pass a dependency function to 'Security' and also pass a list of scopes as the 'scopes' parameter. Security is actually a subclass of Depends with one extra parameter for scope declaration.

SecurityScopes class

Import 'SecurityScopes' from 'fastapi.security'. It is a special parameter type similar to 'Request' that provides access to security scope information. The 'SecurityScopes' object has a 'scopes' property containing a list of all scopes required by the current dependency and all dependencies that depend on it. It also provides a 'scope_str' attribute with scopes separated by spaces as a single string.

SecurityScopes scopes aggregation in dependency tree

SecurityScopes aggregates scopes from the entire dependency tree. For a given path operation, security_scopes.scopes will contain all scopes declared by the path operation itself and all scopes declared in the dependency chain leading to the current dependency function. The same dependency function can have different scopes for different path operations based on their respective dependency trees.

OAuth2PasswordRequestForm scopes property

OAuth2PasswordRequestForm includes a 'scopes' property which is a list of strings containing each scope received in the request. These scopes can be extracted and returned as part of the JWT token.

Adding scopes to JWT token

When returning a JWT token from the token path operation, include the requested scopes as part of the token data. For security, you should validate that users can only receive scopes they are actually able to have or predefined scopes, rather than directly adding all scopes received in the request.

Verify scopes in token validation

When validating a JWT token in a security dependency, verify that all scopes required by the dependency and its dependants are included in the scopes provided in the token. If required scopes are missing, raise an HTTPException. Include the required scopes as a space-separated string in the WWW-Authenticate header of the exception.

Pydantic validation for token data with scopes

Create a Pydantic model like 'TokenData' that includes a 'scopes' property (a list of strings) along with other token fields like 'username'. Validate the token data against this model to ensure the scopes are exactly a list of strings and not other types, which prevents security risks.

WWW-Authenticate header with scopes

When raising an HTTPException for missing scopes, include the required scopes as a space-separated string in the 'WWW-Authenticate' header. This follows the OAuth2 specification.

SecurityScopes usage at multiple levels

SecurityScopes can be used at any point in the dependency tree and in multiple places, not just at the 'root' dependency. It will always contain the security scopes declared in the current Security dependencies and all dependants for that specific path operation and dependency tree.

Scope verification in central dependency

You can use SecurityScopes to verify that a token has required scopes in a central dependency function, while declaring different scope requirements in different path operations. Each path operation will check scopes independently based on its own dependency tree.

OAuth2 password flow for first-party applications

The OAuth2 password flow is appropriate when logging in to your own application with your own frontend because you can trust it to receive the username and password. For OAuth2 applications where third parties connect, use other flows like implicit or code flow instead.

FastAPI OAuth2 flows utilities

FastAPI includes utilities for all OAuth2 authentication flows in the 'fastapi.security.oauth2' module.

Security in decorator dependencies parameter

You can use Security with scopes in the decorator's 'dependencies' parameter, the same way you can use Depends.

FastAPI strict Content-Type checking default

By default, FastAPI uses strict Content-Type header checking for JSON request bodies. JSON requests must include a valid Content-Type header (e.g. application/json) in order for the body to be parsed as JSON.

CSRF protection through strict Content-Type checking

Strict Content-Type checking in FastAPI provides protection against Cross-Site Request Forgery (CSRF) attacks. This protection is relevant in a specific scenario: when an application runs locally or on an internal network without authentication, relying on network access as the only protection. In this case, strict Content-Type checking prevents browsers from sending requests without the Content-Type header, which is necessary for the CSRF attack to work.

CSRF attack scenario: no Content-Type and no authentication

Browser-based CSRF attacks exploit the fact that browsers allow scripts to send requests without CORS preflight checks when the request does not have a Content-Type header (e.g. using fetch() with a Blob body) and does not send any authentication credentials. A malicious website can send requests to a local application via fetch() with a Blob body, and the browser will not trigger a CORS preflight because no authentication is required and the missing Content-Type header makes the browser think it is not sending JSON.

When CSRF attacks through Content-Type bypass are relevant

CSRF attacks that exploit missing Content-Type headers are mainly relevant when the application is running locally (e.g. on localhost) or in an internal network, and the application does not have any authentication set up, trusting that any request from the same network can be trusted. On the open internet, this attack is not relevant because attackers do not need browser interaction to send requests to an API, and privileged endpoints would already be secured with authentication.

Disable strict Content-Type checking with strict_content_type parameter

To support clients that do not send a Content-Type header, you can disable strict Content-Type checking by setting strict_content_type=False on the FastAPI application. With this setting, requests without a Content-Type header will have their body parsed as JSON, matching the behavior of older FastAPI versions.

strict_content_type parameter added in FastAPI 0.132.0

The strict_content_type configuration and the related behavior of strict Content-Type checking was added in FastAPI version 0.132.0.

Give your agent this brain