From f6f3bbc2709bff3f886f1bb3e71c19b786d51336 Mon Sep 17 00:00:00 2001
From: fastapi-users-ci As we said, a backend is the combination of a transport and a strategy. That way, you can create a complete strategy exactly fitting your needs. For this, you have to use the As you can see, instantiation is quite simple. It accepts the following arguments: You can have as many authentication backends as you wish. You'll then have to pass those backends to your FastAPI Users allows you to plug in several authentication methods. You can have several authentication methods, e.g. a cookie authentication for browser-based queries and a JWT token authentication for pure API queries. When checking authentication, each method is run one after the other. The first method yielding a user wins. If no method yields a user, an For each backend, you'll be able to add a router with the corresponding An authentication backend is composed of two parts: It manages how the token will be carried over the request. We currently provide two methods: The token will be sent through an Pros and cons ➡️ Use it if you want to implement a mobile application or a pure REST API. The token will be sent through a cookie. Pros and cons ➡️ Use it if you want to implement a web frontend. It manages how the token is generated and secured. We currently provide three methods: The token is self-contained in a JSON Web Token. Pros and cons ➡️ Use it if you want to get up-and-running quickly. The token is stored in a table (or collection) in your database. Pros and cons ➡️ Use it if you want maximum flexibility in your token management. The token is stored in a Redis key-store. Pros and cons ➡️ Use it if you want maximum performance while being able to invalidate tokens. The most natural way for storing tokens is of course the very same database you're using for your application. In this strategy, we set up a table (or collection) for storing those tokens with the associated user id. On each request, we try to retrive this token from the database to get the corresponding user id. The configuration of this strategy is a bit more complex than the others as it requires you to configure models and a database adapter, exactly like we did for users. An access token will be structured like this in your database: We are providing a base model with those fields for each database we are supporting. We'll expand from the basic SQLAlchemy configuration. We define an We define a dependency to instantiate the By default, we use UUID as a primary key ID for your user, so we follow the same convention to define the foreign key pointing to the user. If you want to use another type, like an auto-incremented integer, you can use Notice that We'll expand from the basic Beanie configuration. We define an We define a dependency to instantiate the As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. As you can see here, this pattern allows us to dynamically inject a connection to the database. On logout, this strategy will delete the token from the database. JSON Web Token (JWT) is an internet standard for creating access tokens based on JSON. They don't need to be stored in a database: the data is self-contained inside and cryptographically signed. As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. For On logout, this strategy won't do anything. Indeed, a JWT can't be invalidated on the server-side: it's valid until it expires. Redis is an ultra-fast key-store database. As such, it's a good candidate for token management. In this strategy, a token is generated and associated with the user id. in the database. On each request, we try to retrieve this token from Redis to get the corresponding user id. You should install the library with the optional dependencies for Redis: As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. On logout, this strategy will delete the token from the Redis store. With this transport, the token is expected inside the As you can see, instantiation is quite simple. It accepts the following arguments: This method will return the in the following form upon successful login: Check documentation about login route. The logout method with this transport returns nothing. This method expects that you provide a Cookies are an easy way to store stateful information into the user browser. Thus, it is more useful for browser-based navigation (e.g. a front-end app making API requests) rather than pure API interaction. As you can see, instantiation is quite simple. It accepts the following arguments: This method will return a response with a valid Check documentation about login route. This method will remove the authentication cookie: Check documentation about logout route. This method expects that you provide a valid cookie in the headers. FastAPI Users provides the necessary tools to work with MongoDB databases using the Beanie ODM. The first thing to do is to create a MongoDB connection using mongodb/motor (automatically installed with Beanie). You can choose any name for the database. As for any Beanie ODM model, we'll create a As you can see, FastAPI Users provides a base class that will include base fields for our Document ID is a MongoDB ObjectID Beanie automatically manages document ID by encoding/decoding MongoDB ObjectID. If you want to use another type, like UUID, you can override the Notice that Info The base class is configured to automatically create a unique index on The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency. Notice that we pass a reference to the When initializing your FastAPI app, it's important that you initialize Beanie so it can discover your models. We can achieve this using a startup event handler on the FastAPI app: This is the This is the Beanie FastAPI Users provides the necessary tools to work with SQL databases thanks to SQLAlchemy ORM with asyncio. To work with your DBMS, you'll need to install the corresponding asyncio driver. The common choices are: Examples of For the sake of this tutorial from now on, we'll use a simple SQLite database. As for any SQLAlchemy ORM model, we'll create a As you can see, FastAPI Users provides a base class that will include base fields for our Primary key is defined as UUID By default, we use UUID as a primary key ID for your user. If you want to use another type, like an auto-incremented integer, you can use Notice that We'll now create an utility function to create all the defined tables. This function can be called, for example, during the initialization of your FastAPI app. Warning In production, it's strongly recommended to setup a migration system to update your SQL schemas. See Alembic. The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency. Notice that we define first a It's then used inside the Here is a full working example with JWT authentication to help get you started. Warning Notice that SECRET should be changed to a strong passphrase.
+Insecure passwords may give attackers full access to your database. You're ready to go! Be sure to check the Usage section to understand how to work with FastAPI Users. FastAPI Users provides an optional OAuth2 authentication support. It relies on HTTPX OAuth library, which is a pure-async implementation of OAuth2. You should install the library with the optional dependencies for OAuth: You first need to get an HTTPX OAuth client instance. Read the documentation for more information. You'll need to define the SQLAlchemy model for storing OAuth accounts. We provide a base one for this: Notice that we also manually added a Besides, when instantiating the database adapter, we need pass this SQLAlchemy model as third argument. Primary key is defined as UUID By default, we use UUID as a primary key ID for your user. If you want to use another type, like an auto-incremented integer, you can use Notice that The advantage of MongoDB is that you can easily embed sub-objects in a single document. That's why the configuration for Beanie is quite simple. All we need to do is to define another class to structure an OAuth account object. It's worth to note that Once you have a Tip If you have several OAuth clients and/or several authentication backends, you'll need to create a router for each pair you want to support. If a user with the same e-mail address already exists, an HTTP 400 error will be raised by default. You can however choose to automatically link this OAuth account to the existing user account by setting the Bear in mind though that it can lead to security breaches if the OAuth provider does not validate e-mail addresses. How? We also provide a router to associate an already authenticated user with an OAuth account. After this association, the user will be able to authenticate with this OAuth provider. Notice that, just like for the Users router, you have to pass the Warning Notice that SECRET should be changed to a strong passphrase.
+Insecure passwords may give attackers full access to your database. The schema below shows you how the library is structured and how each part fit together. FastAPI Users is compatible with various databases and ORM. To build the interface between those database tools and the library, we provide database adapters classes that you need to instantiate and configure. Authentication backends define the way users sessions are managed in your app, like access tokens or cookies. They are composed of two parts: a transport, which is how the token will be carried over the requests (e.g. cookies, headers...) and a strategy, which is how the token will be generated and secured (e.g. a JWT, a token in database...). ➡️ Configure the authentication backends The This FastAPI is heavily using Pydantic models to validate request payloads and serialize responses. FastAPI Users is no exception and will expect you to provide Pydantic schemas representing a user when it's read, created and updated. Finally, By default, FastAPI Users will use the BCrypt algorithm to hash and salt passwords before storing them in the database. The implementation is provided by Passlib, a battle-tested Python library for password hashing. If you need to support other hashing algorithms, you can customize the For this, you'll need to instantiate the Finally, pass the Password hashes are automatically upgraded FastAPI Users takes care of upgrading the password hash to a more recent algorithm when needed. Typically, when a user logs in, we'll check if the password hash algorithm is deprecated. If it is, we take the opportunity of having the password in plain-text at hand (since the user just logged in!) to hash it with a better algorithm and update it in database. Dependencies for alternative algorithms are not included by default FastAPI Users won't install required dependencies to make other algorithms like Argon2 work. It's up to you to install them. If you don't wist to use Passlib at all – which we don't recommend unless you're absolutely sure of what you're doing — you can implement your own The auth router will generate Check the routes usage to learn how to use them. You can require the user to be verified (i.e. We're almost there! The last step is to configure the Configure Typing: User and ID generic types are expected You can see that we define two generic types when instantiating: It'll help you to have good type-checking and auto-completion. This helper class will let you generate useful routers to setup the authentication system. Each of them is optional, so you can pick only the one that you are interested in! Here are the routers provided: You should check out each of them to understand how to use them. The register router will generate a Check the routes usage to learn how to use them. The reset password router will generate Check the routes usage to learn how to use them. This router provides routes to manage users. Check the routes usage to learn how to use them. You can require the user to be verified (i.e. This router provides routes to manage user email verification. Check the routes usage to learn how to use them. 👏👏👏 A big thank you to Edd Salkield and Mark Todd who worked hard on this feature! FastAPI is heavily using Pydantic models to validate request payloads and serialize responses. FastAPI Users is no exception and will expect you to provide Pydantic schemas representing a user when it's read, created and updated. It's different from your FastAPI Users provides a base structure to cover its needs. It is structured like this: There are four Pydantic models variations provided as mixins: You should define each of those variations, inheriting from each mixin: Typing: ID generic type is expected You can see that we define a generic type when extending the You can of course add your own properties there to fit to your needs. In the example below, we add a required string property, Make sure to mirror this in your database model The The It's designed to be easily extensible and customizable so that you can integrate your very own logic. You should define your own version of the As you can see, you have to define here various attributes and methods. You can find the complete list of those below. Typing: User and ID generic types are expected You can see that we define two generic types when extending the base class: It'll help you to have good type-checking and auto-completion when implementing the custom methods. Since the user ID is fully generic, we need a way to parse it reliably when it'll come from API requests, typically as URL path attributes. That's why we added the Of course, it's important that this logic matches the type of your ID. To help you with this, we provide mixins for the most common cases: Inheritance order matters Notice in your example that the mixin comes first in our If you need another type of ID, you can simply overload the The Notice that we use the Validate a password. Arguments Output This function should return Example Perform logic after successful user registration. Typically, you'll want to send a welcome e-mail or add it to your marketing analytics pipeline. Arguments Example Perform logic after successful user update. It may be useful, for example, if you wish to update your user in a data analytics or customer success platform. Arguments Example Perform logic after a successful user login. It may be useful for custom logic or processes triggered by new logins, for example a daily login reward or for analytics. Arguments Example Perform logic after successful verification request. Typically, you'll want to send an e-mail with the link (and the token) that allows the user to verify their e-mail. Arguments Example Perform logic after successful user verification. This may be useful if you wish to send another e-mail or store this information in a data analytics or customer success platform. Arguments Example Perform logic after successful forgot password request. Typically, you'll want to send an e-mail with the link (and the token) that allows the user to reset their password. Arguments Example Perform logic after successful password reset. For example, you may want to send an e-mail to the concerned user to warn him that their password has been changed and that they should take action if they think they have been hacked. Arguments Example Perform logic before user delete. For example, you may want to valide user resource integrity to see if any related user resource need to be marked inactive, or delete
+them recursively. Arguments Example Perform logic after user delete. For example, you may want to send an email to the administrator about the event. Arguments Example Sometimes, you'll need to create a user programmatically in the code rather than passing by the REST API endpoint. To do this, we'll create a function that you can call from your code. In this context, we are outside the dependency injection mechanism of FastAPI, so we have to take care of instantiating the For this cookbook, we'll consider you are starting from the SQLAlchemy full example, but it'll be rather similar for other DBMS. Generally, FastAPI dependencies are defined as generators, using the In Python, when we want to use a generator, we have to use a In the following sample, we import our dependencies and create a context manager version using I have other dependencies Since FastAPI Users fully embraces dependency injection, you may have more arguments passed to your database or user manager dependencies. It's important then to not forget anyone. Once again, outside the dependency injection system, you are responsible of instantiating everything yourself. We are now ready to write a function. The example below shows you a basic example but you can of course adapt it to your own needs. The key part here is once again to take care of opening every context managers and pass them every required arguments, as the dependency manager would do. You can now easily use it in a script. For example:
+
+ Ready-to-use and customizable users management for FastAPI
+ Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: https://github.com/fastapi-users/fastapi-users Add quickly a registration and authentication system to your FastAPI project. FastAPI Users is designed to be as customizable and adaptable as possible.
+ Implementing registration, login, social auth is hard and painful. We know it. With our highly secure and open-source users management platform, you can focus on your app while staying in control of your users data. It's free! Thanks goes to these wonderful people (emoji key): This project follows the all-contributors specification. Contributions of any kind welcome! We use Hatch to manage the development environment and production build. Ensure it's installed on your system. You can run all the tests with: Execute the following command to apply You can serve the documentation locally with the following command: The documentation will be available on http://localhost:8000. This project is licensed under the terms of the MIT license. You can add FastAPI Users to your FastAPI project in a few easy steps. First of all, install the dependency: Information on installing with proper database support can be found in the Redis section. Information on installing with proper database support can be found in the OAuth2 section. That's it! In the next section, we'll have an overview of how things work. 1.0 version introduces major breaking changes that need you to update some of your code and migrate your data. Users and OAuth accounts id. are now represented as real UUID objects instead of plain strings. This change was introduced to leverage efficient storage and indexing for DBMS that supports UUID (especially PostgreSQL and Mongo). If you were doing comparison betwen a user id. and a string (in unit tests for example), you should now cast the id. to string: If you were refering to user id. in your Pydantic models, the field should now be of To avoid any issues, it's recommended to use the This parameter controls how the UUID values will be encoded in the database. By default, it's set to Id. were before stored as strings in the database. You should make a migration to convert string data to UUID data. Danger Scripts below are provided as guidelines. Please review them carefully, adapt them and check that they are working on a test database before applying them to production. BE CAREFUL. THEY CAN DESTROY YOUR DATA.. PostgreSQL supports UUID type. If not already, you should enable the To convert the existing id. string column, we can: MySQL doesn't support UUID type. We'll just convert the column to For MongoDB, we can use a You now have the responsibility to wire the routers. FastAPI Users doesn't give a bloated users router anymore. Event handlers are also removed. You have to provide your "after-" logic as a parameter of the router generator. Important things to notice: To be fully compatible with Swagger authentication, the output of a successful login operation with the JWT authentication backend has changed: Before After Make sure to update your clients to read the token in the right property. Before 3.x.x, the local part (before the @) of the email address was case-sensitive. Therefore, After 3.x.x, users are fetched from the database with a case-insensitive email search. Bear in mind though that if the user registers with the email Danger It's super important then, before you upgrade to 3.x.x that you check if there are several users with the same email with different cases ; and that you merge or delete those accounts. Before 4.x.x, the If you use SQLAlchemy or Tortoise databases adapters, you'll have to make a migration to update your database schema. Starting 5.x.x., there is a new e-mail verification feature. Even if optional, the If you use SQLAlchemy or Tortoise databases adapters, you'll have to make a migration to update your database schema. Version 8 includes the biggest code changes since version 1. We reorganized lot of parts of the code to make it even more modular and integrate more into the dependency injection system of FastAPI. Most importantly, you need now to implement a Before, event handlers like Now, they should be methods of the You can read more in the Before, password validation was defined in its own function that was passed as argument of Now, it should be a method of the You can read more in the Before, verify token and lifetime parameters were passed as argument of Now, they should be defined as attributes of the You can read more in the Before, reset password token and lifetime parameters were passed as argument of Now, they should be defined as attributes of the You can read more in the Before, we advised to directly instantiate the database adapter class. Now, it should be instantiated inside a dependency that you define yourself. The benefit of this is that it lives in the dependency injection system of FastAPI, allowing you to have more dynamic logic to create your instance. Before, the database adapter instance was passed as argument of Now, you should define a You can read more in the If you're unsure or a bit lost, make sure to check the full working examples. Version 9 revamps the authentication backends: we splitted the logic of a backend into two: the transport, which is how the token will be carried over the request and the strategy, which is how the token is generated and secured. The benefit of this is that we'll soon be able to propose new strategies, like database session tokens, without having to repeat the transport logic which remains the same. You now have to generate an authentication backend with a transport and a strategy. Warning There is no default Warning There is no default Tip Notice that the strategy is the same for both authentication backends. That's the beauty of this approach: the token generation is decoupled from its transport. Before, a single OAuth router was enough to login with any of your authentication backend. Now, you need to generate a router for each of your backends. The consequence of this is that you don't need to specify the authentication backend when making a request to If you're unsure or a bit lost, make sure to check the full working examples. Version 10 marks important changes in how we manage User models and their ID. Before, we were relying only on Pydantic models to work with users. In particular the Now, FastAPI Users is designed to always return you a native object for your ORM model, whether it's an SQLAlchemy model or a Beanie document. Pydantic models are now only used for validation and serialization inside the API. Before, we were forcing the use of UUID as primary key ID; a consequence of the design above. This proved to be quite problematic on some databases, like MongoDB which uses a special ObjectID format by default. Some SQL folks also prefer to use traditional auto-increment integers. Now, FastAPI Users is designed to use generic ID type. It means that you can use any type you want for your user's ID. By default, SQLAlchemy adapter still use UUID; but you can quite easily switch to another thing, like an integer. Beanie adapter for MongoDB will use native ObjectID by default, but it also can be overriden. As you may have guessed, those changes imply quite a lot of breaking changes. We've removed the old SQLAlchemy dependency support, so the dependency is now The User model base class for SQLAlchemy slightly changed to support UUID by default. We changed the name of the class from Instantiating the MongoDB support is now only provided through Beanie ODM. Even if you don't use it for the rest of your project, it's a very light addition that shouldn't interfere much. You now need to define a proper User model using Beanie. ID are now ObjectID by default By default, User ID will now be native MongoDB ObjectID. If you don't want to make the transition and keep UUID you can do so by overriding the Beanie also needs to be initialized in a startup event handler of your FastAPI app: Unfortunately, we sometimes need to make difficult choices to keep things sustainable. That's why we decided to not support Tortoise ORM and ormar anymore. It appeared they were not widely used. You can still add support for those ORM yourself by implementing the necessary adapter. You can take inspiration from the SQLAlchemy one. There is some slight changes on the Generic typing now expects your native User model class and the type of ID. The If you need to support other types of ID, you can read more about it in the dedicated section. To better distinguish them from the ORM models, Pydantic models are now called schemas. We changed the name of Besides, the Pydantic schemas are now way less important in this new design. As such, you don't need to pass them when initializing the As a consequence, those schemas need to be passed when initializing the router that needs them: If you're unsure or a bit lost, make sure to check the full working examples. Ready-to-use and customizable users management for FastAPI Documentation: https://fastapi-users.github.io/fastapi-users/ Source Code: https://github.com/fastapi-users/fastapi-users Add quickly a registration and authentication system to your FastAPI project. FastAPI Users is designed to be as customizable and adaptable as possible. Implementing registration, login, social auth is hard and painful. We know it. With our highly secure and open-source users management platform, you can focus on your app while staying in control of your users data. It's free! Thanks goes to these wonderful people (emoji key): This project follows the all-contributors specification. Contributions of any kind welcome! We use Hatch to manage the development environment and production build. Ensure it's installed on your system. You can run all the tests with: Execute the following command to apply You can serve the documentation locally with the following command: The documentation will be available on http://localhost:8000. This project is licensed under the terms of the MIT license. You can add FastAPI Users to your FastAPI project in a few easy steps. First of all, install the dependency: Information on installing with proper database support can be found in the Redis section. Information on installing with proper database support can be found in the OAuth2 section. That's it! In the next section, we'll have an overview of how things work. Here is a full working example with JWT authentication to help get you started. Warning Notice that SECRET should be changed to a strong passphrase. Insecure passwords may give attackers full access to your database. Open Open You're ready to go! Be sure to check the Usage section to understand how to work with FastAPI Users. FastAPI Users provides an optional OAuth2 authentication support. It relies on HTTPX OAuth library, which is a pure-async implementation of OAuth2. You should install the library with the optional dependencies for OAuth: You first need to get an HTTPX OAuth client instance. Read the documentation for more information. You'll need to define the SQLAlchemy model for storing OAuth accounts. We provide a base one for this: Notice that we also manually added a Besides, when instantiating the database adapter, we need pass this SQLAlchemy model as third argument. Primary key is defined as UUID By default, we use UUID as a primary key ID for your user. If you want to use another type, like an auto-incremented integer, you can use Notice that The advantage of MongoDB is that you can easily embed sub-objects in a single document. That's why the configuration for Beanie is quite simple. All we need to do is to define another class to structure an OAuth account object. It's worth to note that Once you have a Tip If you have several OAuth clients and/or several authentication backends, you'll need to create a router for each pair you want to support. If a user with the same e-mail address already exists, an HTTP 400 error will be raised by default. You can however choose to automatically link this OAuth account to the existing user account by setting the Bear in mind though that it can lead to security breaches if the OAuth provider does not validate e-mail addresses. How? We also provide a router to associate an already authenticated user with an OAuth account. After this association, the user will be able to authenticate with this OAuth provider. Notice that, just like for the Users router, you have to pass the Warning Notice that SECRET should be changed to a strong passphrase. Insecure passwords may give attackers full access to your database. Open Open The schema below shows you how the library is structured and how each part fit together. FastAPI Users is compatible with various databases and ORM. To build the interface between those database tools and the library, we provide database adapters classes that you need to instantiate and configure. \u27a1\ufe0f I'm using SQLAlchemy \u27a1\ufe0f I'm using Beanie Authentication backends define the way users sessions are managed in your app, like access tokens or cookies. They are composed of two parts: a transport, which is how the token will be carried over the requests (e.g. cookies, headers...) and a strategy, which is how the token will be generated and secured (e.g. a JWT, a token in database...). \u27a1\ufe0f Configure the authentication backends The This \u27a1\ufe0f Configure FastAPI is heavily using Pydantic models to validate request payloads and serialize responses. FastAPI Users is no exception and will expect you to provide Pydantic schemas representing a user when it's read, created and updated. \u27a1\ufe0f Configure schemas Finally, \u27a1\ufe0f Configure By default, FastAPI Users will use the BCrypt algorithm to hash and salt passwords before storing them in the database. The implementation is provided by Passlib, a battle-tested Python library for password hashing. If you need to support other hashing algorithms, you can customize the For this, you'll need to instantiate the Finally, pass the Password hashes are automatically upgraded FastAPI Users takes care of upgrading the password hash to a more recent algorithm when needed. Typically, when a user logs in, we'll check if the password hash algorithm is deprecated. If it is, we take the opportunity of having the password in plain-text at hand (since the user just logged in!) to hash it with a better algorithm and update it in database. Dependencies for alternative algorithms are not included by default FastAPI Users won't install required dependencies to make other algorithms like Argon2 work. It's up to you to install them. If you don't wist to use Passlib at all \u2013 which we don't recommend unless you're absolutely sure of what you're doing \u2014 you can implement your own FastAPI is heavily using Pydantic models to validate request payloads and serialize responses. FastAPI Users is no exception and will expect you to provide Pydantic schemas representing a user when it's read, created and updated. It's different from your FastAPI Users provides a base structure to cover its needs. It is structured like this: There are four Pydantic models variations provided as mixins: You should define each of those variations, inheriting from each mixin: Typing: ID generic type is expected You can see that we define a generic type when extending the You can of course add your own properties there to fit to your needs. In the example below, we add a required string property, Make sure to mirror this in your database model The The It's designed to be easily extensible and customizable so that you can integrate your very own logic. You should define your own version of the As you can see, you have to define here various attributes and methods. You can find the complete list of those below. Typing: User and ID generic types are expected You can see that we define two generic types when extending the base class: It'll help you to have good type-checking and auto-completion when implementing the custom methods. Since the user ID is fully generic, we need a way to parse it reliably when it'll come from API requests, typically as URL path attributes. That's why we added the Of course, it's important that this logic matches the type of your ID. To help you with this, we provide mixins for the most common cases: Inheritance order matters Notice in your example that the mixin comes first in our If you need another type of ID, you can simply overload the The Notice that we use the Validate a password. Arguments Output This function should return Example Perform logic after successful user registration. Typically, you'll want to send a welcome e-mail or add it to your marketing analytics pipeline. Arguments Example Perform logic after successful user update. It may be useful, for example, if you wish to update your user in a data analytics or customer success platform. Arguments Example Perform logic after a successful user login. It may be useful for custom logic or processes triggered by new logins, for example a daily login reward or for analytics. Arguments Example Perform logic after successful verification request. Typically, you'll want to send an e-mail with the link (and the token) that allows the user to verify their e-mail. Arguments Example Perform logic after successful user verification. This may be useful if you wish to send another e-mail or store this information in a data analytics or customer success platform. Arguments Example Perform logic after successful forgot password request. Typically, you'll want to send an e-mail with the link (and the token) that allows the user to reset their password. Arguments Example Perform logic after successful password reset. For example, you may want to send an e-mail to the concerned user to warn him that their password has been changed and that they should take action if they think they have been hacked. Arguments Example Perform logic before user delete. For example, you may want to valide user resource integrity to see if any related user resource need to be marked inactive, or delete them recursively. Arguments Example Perform logic after user delete. For example, you may want to send an email to the administrator about the event. Arguments Example FastAPI Users allows you to plug in several authentication methods. You can have several authentication methods, e.g. a cookie authentication for browser-based queries and a JWT token authentication for pure API queries. When checking authentication, each method is run one after the other. The first method yielding a user wins. If no method yields a user, an For each backend, you'll be able to add a router with the corresponding An authentication backend is composed of two parts: It manages how the token will be carried over the request. We currently provide two methods: The token will be sent through an Pros and cons \u27a1\ufe0f Use it if you want to implement a mobile application or a pure REST API. The token will be sent through a cookie. Pros and cons \u27a1\ufe0f Use it if you want to implement a web frontend. It manages how the token is generated and secured. We currently provide three methods: The token is self-contained in a JSON Web Token. Pros and cons \u27a1\ufe0f Use it if you want to get up-and-running quickly. The token is stored in a table (or collection) in your database. Pros and cons \u27a1\ufe0f Use it if you want maximum flexibility in your token management. The token is stored in a Redis key-store. Pros and cons \u27a1\ufe0f Use it if you want maximum performance while being able to invalidate tokens. As we said, a backend is the combination of a transport and a strategy. That way, you can create a complete strategy exactly fitting your needs. For this, you have to use the As you can see, instantiation is quite simple. It accepts the following arguments: You can have as many authentication backends as you wish. You'll then have to pass those backends to your The most natural way for storing tokens is of course the very same database you're using for your application. In this strategy, we set up a table (or collection) for storing those tokens with the associated user id. On each request, we try to retrive this token from the database to get the corresponding user id. The configuration of this strategy is a bit more complex than the others as it requires you to configure models and a database adapter, exactly like we did for users. An access token will be structured like this in your database: We are providing a base model with those fields for each database we are supporting. We'll expand from the basic SQLAlchemy configuration. We define an We define a dependency to instantiate the By default, we use UUID as a primary key ID for your user, so we follow the same convention to define the foreign key pointing to the user. If you want to use another type, like an auto-incremented integer, you can use Notice that We'll expand from the basic Beanie configuration. We define an We define a dependency to instantiate the As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. As you can see here, this pattern allows us to dynamically inject a connection to the database. On logout, this strategy will delete the token from the database. JSON Web Token (JWT) is an internet standard for creating access tokens based on JSON. They don't need to be stored in a database: the data is self-contained inside and cryptographically signed. As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. For On logout, this strategy won't do anything. Indeed, a JWT can't be invalidated on the server-side: it's valid until it expires. Redis is an ultra-fast key-store database. As such, it's a good candidate for token management. In this strategy, a token is generated and associated with the user id. in the database. On each request, we try to retrieve this token from Redis to get the corresponding user id. You should install the library with the optional dependencies for Redis: As you can see, instantiation is quite simple. It accepts the following arguments: Why it's inside a function? To allow strategies to be instantiated dynamically with other dependencies, they have to be provided as a callable to the authentication backend. On logout, this strategy will delete the token from the Redis store. With this transport, the token is expected inside the As you can see, instantiation is quite simple. It accepts the following arguments: This method will return the in the following form upon successful login: Check documentation about login route. The logout method with this transport returns nothing. This method expects that you provide a Cookies are an easy way to store stateful information into the user browser. Thus, it is more useful for browser-based navigation (e.g. a front-end app making API requests) rather than pure API interaction. As you can see, instantiation is quite simple. It accepts the following arguments: This method will return a response with a valid Check documentation about login route. This method will remove the authentication cookie: Check documentation about logout route. This method expects that you provide a valid cookie in the headers. FastAPI Users provides the necessary tools to work with MongoDB databases using the Beanie ODM. The first thing to do is to create a MongoDB connection using mongodb/motor (automatically installed with Beanie). You can choose any name for the database. As for any Beanie ODM model, we'll create a As you can see, FastAPI Users provides a base class that will include base fields for our Document ID is a MongoDB ObjectID Beanie automatically manages document ID by encoding/decoding MongoDB ObjectID. If you want to use another type, like UUID, you can override the Notice that Info The base class is configured to automatically create a unique index on The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency. Notice that we pass a reference to the When initializing your FastAPI app, it's important that you initialize Beanie so it can discover your models. We can achieve this using a startup event handler on the FastAPI app: This is the This is the Beanie FastAPI Users provides the necessary tools to work with SQL databases thanks to SQLAlchemy ORM with asyncio. To work with your DBMS, you'll need to install the corresponding asyncio driver. The common choices are: Examples of For the sake of this tutorial from now on, we'll use a simple SQLite database. As for any SQLAlchemy ORM model, we'll create a As you can see, FastAPI Users provides a base class that will include base fields for our Primary key is defined as UUID By default, we use UUID as a primary key ID for your user. If you want to use another type, like an auto-incremented integer, you can use Notice that We'll now create an utility function to create all the defined tables. This function can be called, for example, during the initialization of your FastAPI app. Warning In production, it's strongly recommended to setup a migration system to update your SQL schemas. See Alembic. The database adapter of FastAPI Users makes the link between your database configuration and the users logic. It should be generated by a FastAPI dependency. Notice that we define first a It's then used inside the We're almost there! The last step is to configure the Configure Typing: User and ID generic types are expected You can see that we define two generic types when instantiating: It'll help you to have good type-checking and auto-completion. This helper class will let you generate useful routers to setup the authentication system. Each of them is optional, so you can pick only the one that you are interested in! Here are the routers provided: You should check out each of them to understand how to use them. The auth router will generate Check the routes usage to learn how to use them. You can require the user to be verified (i.e. The register router will generate a Check the routes usage to learn how to use them. The reset password router will generate Check the routes usage to learn how to use them. This router provides routes to manage users. Check the routes usage to learn how to use them. You can require the user to be verified (i.e. This router provides routes to manage user email verification. Check the routes usage to learn how to use them. \ud83d\udc4f\ud83d\udc4f\ud83d\udc4f A big thank you to Edd Salkield and Mark Todd who worked hard on this feature! Sometimes, you'll need to create a user programmatically in the code rather than passing by the REST API endpoint. To do this, we'll create a function that you can call from your code. In this context, we are outside the dependency injection mechanism of FastAPI, so we have to take care of instantiating the For this cookbook, we'll consider you are starting from the SQLAlchemy full example, but it'll be rather similar for other DBMS. Generally, FastAPI dependencies are defined as generators, using the In Python, when we want to use a generator, we have to use a In the following sample, we import our dependencies and create a context manager version using I have other dependencies Since FastAPI Users fully embraces dependency injection, you may have more arguments passed to your database or user manager dependencies. It's important then to not forget anyone. Once again, outside the dependency injection system, you are responsible of instantiating everything yourself. We are now ready to write a function. The example below shows you a basic example but you can of course adapt it to your own needs. The key part here is once again to take care of opening every context managers and pass them every required arguments, as the dependency manager would do. You can now easily use it in a script. For example: 1.0 version introduces major breaking changes that need you to update some of your code and migrate your data. Users and OAuth accounts id. are now represented as real UUID objects instead of plain strings. This change was introduced to leverage efficient storage and indexing for DBMS that supports UUID (especially PostgreSQL and Mongo). If you were doing comparison betwen a user id. and a string (in unit tests for example), you should now cast the id. to string: If you were refering to user id. in your Pydantic models, the field should now be of To avoid any issues, it's recommended to use the This parameter controls how the UUID values will be encoded in the database. By default, it's set to Id. were before stored as strings in the database. You should make a migration to convert string data to UUID data. Danger Scripts below are provided as guidelines. Please review them carefully, adapt them and check that they are working on a test database before applying them to production. BE CAREFUL. THEY CAN DESTROY YOUR DATA.. PostgreSQL supports UUID type. If not already, you should enable the To convert the existing id. string column, we can: MySQL doesn't support UUID type. We'll just convert the column to For MongoDB, we can use a You now have the responsibility to wire the routers. FastAPI Users doesn't give a bloated users router anymore. Event handlers are also removed. You have to provide your \"after-\" logic as a parameter of the router generator. Important things to notice: To be fully compatible with Swagger authentication, the output of a successful login operation with the JWT authentication backend has changed: Before After Make sure to update your clients to read the token in the right property. Before 3.x.x, the local part (before the @) of the email address was case-sensitive. Therefore, After 3.x.x, users are fetched from the database with a case-insensitive email search. Bear in mind though that if the user registers with the email Danger It's super important then, before you upgrade to 3.x.x that you check if there are several users with the same email with different cases ; and that you merge or delete those accounts. Before 4.x.x, the If you use SQLAlchemy or Tortoise databases adapters, you'll have to make a migration to update your database schema. Starting 5.x.x., there is a new e-mail verification feature. Even if optional, the If you use SQLAlchemy or Tortoise databases adapters, you'll have to make a migration to update your database schema. Version 8 includes the biggest code changes since version 1. We reorganized lot of parts of the code to make it even more modular and integrate more into the dependency injection system of FastAPI. Most importantly, you need now to implement a Before, event handlers like Now, they should be methods of the You can read more in the Before, password validation was defined in its own function that was passed as argument of Now, it should be a method of the You can read more in the Before, verify token and lifetime parameters were passed as argument of Now, they should be defined as attributes of the You can read more in the Before, reset password token and lifetime parameters were passed as argument of Now, they should be defined as attributes of the You can read more in the Before, we advised to directly instantiate the database adapter class. Now, it should be instantiated inside a dependency that you define yourself. The benefit of this is that it lives in the dependency injection system of FastAPI, allowing you to have more dynamic logic to create your instance. \u27a1\ufe0f I'm using SQLAlchemy \u27a1\ufe0f I'm using MongoDB \u27a1\ufe0f I'm using Tortoise ORM \u27a1\ufe0f I'm using ormar Before, the database adapter instance was passed as argument of Now, you should define a You can read more in the If you're unsure or a bit lost, make sure to check the full working examples. Version 9 revamps the authentication backends: we splitted the logic of a backend into two: the transport, which is how the token will be carried over the request and the strategy, which is how the token is generated and secured. The benefit of this is that we'll soon be able to propose new strategies, like database session tokens, without having to repeat the transport logic which remains the same. You now have to generate an authentication backend with a transport and a strategy. Warning There is no default Warning There is no default Tip Notice that the strategy is the same for both authentication backends. That's the beauty of this approach: the token generation is decoupled from its transport. Before, a single OAuth router was enough to login with any of your authentication backend. Now, you need to generate a router for each of your backends. The consequence of this is that you don't need to specify the authentication backend when making a request to If you're unsure or a bit lost, make sure to check the full working examples. Version 10 marks important changes in how we manage User models and their ID. Before, we were relying only on Pydantic models to work with users. In particular the Now, FastAPI Users is designed to always return you a native object for your ORM model, whether it's an SQLAlchemy model or a Beanie document. Pydantic models are now only used for validation and serialization inside the API. Before, we were forcing the use of UUID as primary key ID; a consequence of the design above. This proved to be quite problematic on some databases, like MongoDB which uses a special ObjectID format by default. Some SQL folks also prefer to use traditional auto-increment integers. Now, FastAPI Users is designed to use generic ID type. It means that you can use any type you want for your user's ID. By default, SQLAlchemy adapter still use UUID; but you can quite easily switch to another thing, like an integer. Beanie adapter for MongoDB will use native ObjectID by default, but it also can be overriden. As you may have guessed, those changes imply quite a lot of breaking changes. We've removed the old SQLAlchemy dependency support, so the dependency is now The User model base class for SQLAlchemy slightly changed to support UUID by default. We changed the name of the class from Instantiating the MongoDB support is now only provided through Beanie ODM. Even if you don't use it for the rest of your project, it's a very light addition that shouldn't interfere much. You now need to define a proper User model using Beanie. ID are now ObjectID by default By default, User ID will now be native MongoDB ObjectID. If you don't want to make the transition and keep UUID you can do so by overriding the Beanie also needs to be initialized in a startup event handler of your FastAPI app: Unfortunately, we sometimes need to make difficult choices to keep things sustainable. That's why we decided to not support Tortoise ORM and ormar anymore. It appeared they were not widely used. You can still add support for those ORM yourself by implementing the necessary adapter. You can take inspiration from the SQLAlchemy one. There is some slight changes on the Generic typing now expects your native User model class and the type of ID. The If you need to support other types of ID, you can read more about it in the dedicated section. To better distinguish them from the ORM models, Pydantic models are now called schemas. We changed the name of Besides, the Pydantic schemas are now way less important in this new design. As such, you don't need to pass them when initializing the As a consequence, those schemas need to be passed when initializing the router that needs them: If you're unsure or a bit lost, make sure to check the full working examples. FastAPI Users provides a dependency callable to easily inject authenticated user in your routes. They are available from your Tip For more information about how to make an authenticated request to your API, check the documentation of your Authentication method. Return a dependency callable to retrieve currently authenticated user, passing the following parameters: Create it once and reuse it This function is a factory, a function returning another function \ud83e\udd2f It's this returned function that will be the dependency called by FastAPI in your API routes. To avoid having to generate it on each route and avoid issues when unit testing, it's strongly recommended that you assign the result in a variable and reuse it at will in your routes. The examples below demonstrate this pattern. Warning This is an advanced feature for cases where you have several authentication backends that are enabled conditionally. In most cases, you won't need this option. If you don't need the user in the route logic, you can use this syntax: You can read more about this in FastAPI docs. This page will present you a complete registration and authentication flow once you've setup FastAPI Users. Each example will be presented with a First step, of course, is to register as a user. You'll get a JSON response looking like this: Info Several things to bear in mind: Now, you can login as this new user. You can generate a login route for each authentication backend. Each backend will have a different response. Warning Notice that we don't send it as a JSON payload here but with form data instead. Also, the email is provided by a field named You'll get a JSON response looking like this: You can use this token to make authenticated requests as the user Warning Notice that we don't send it as a JSON payload here but with form data instead. Also, the email is provided by a field named You'll get an empty response. However, the response will come with a You can make authenticated requests as the user Tip The cookie backend is more suited for browsers, as they handle them automatically. This means that if you make a login request in the browser, it will automatically store the cookie and automatically send it in subsequent requests. Now that we can authenticate, we can get our own profile data. Depending on your authentication backend, the method to authenticate the request will vary. We'll stick with JWT from now on. You'll get a JSON response looking like this: Tip If you use one of the dependency callable to protect one of your own endpoint, you'll have to authenticate exactly in the same way. We can also update our own profile. For example, we can change our password like this. You'll get a JSON response looking like this: Info Once again, the user cannot set If you want to manage the users of your application, you'll have to become a superuser. The very first superuser can only be set at database level: open it through a CLI or a GUI, find your user and set the Now that you are a superuser, you can leverage the power of superuser routes. You can for example get the profile of any user in the database given its id. You'll get a JSON response looking like this: We can now update the profile of any user. For example, we can promote it as superuser. You'll get a JSON response looking like this: Finally, we can delete a user. You'll get an empty response. We can also end the session. You'll get an empty response. That's it! You now have a good overview of how you can manage the users through the API. Be sure to check the Routes page to have all the details about each endpoints. You'll find here the routes exposed by FastAPI Users. Note that you can also review them through the interactive API docs. Each authentication backend you generate a router for will produce the following routes. Take care about the prefix you gave it, especially if you have several backends. Login a user against the method named Payload ( Bad credentials or the user is inactive. The user is not verified. Logout the authenticated user against the method named Missing token or inactive user. The logout process was successful. Register a new user. Will call the Payload A user already exists with this email. Password validation failed. Request a reset password procedure. Will generate a temporary token and call the To prevent malicious users from guessing existing users in your database, the route will always return a Payload Reset a password. Requires the token generated by the Payload Bad or expired token. Password validation failed. Request a user to verify their e-mail. Will generate a temporary token and call the To prevent malicious users from guessing existing users in your database, the route will always return a Payload Verify a user. Requires the token generated by the Payload Bad token, not existing user or not the e-mail currently set for the user. The user is already verified. Each OAuth router you define will expose the two following routes. Return the authorization URL for the OAuth service where you should redirect your user. Query parameters Handle the OAuth callback. Query parameters Depending on the situation, several things can happen: Invalid token. The OAuth provider didn't return an e-mail address. Make sure this provider return e-mail address through their API and you have asked for the required scope. Another user with the same e-mail address already exists. User is inactive. Each OAuth association router you define will expose the two following routes. Return the authorization URL for the OAuth service where you should redirect your user. Query parameters Missing token or inactive user. Handle the OAuth callback and add the OAuth account to the current authenticated active user. Query parameters Missing token or inactive user. Invalid token. The OAuth provider didn't return an e-mail address. Make sure this provider return e-mail address through their API and you have asked for the required scope. Return the current authenticated active user. Missing token or inactive user. Update the current authenticated active user. Payload Missing token or inactive user. Password validation failed. A user with this email already exists. 404 - Not found
+
+
+
Create a backend¶
+AuthenticationBackend class.from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy
+
+SECRET = "SECRET"
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+
+name (str): Name of the backend. Each backend should have a unique name.transport (Transport): An instance of a Transport class.get_strategy (Callable[..., Strategy]): A dependency callable returning an instance of a Strategy class.Next steps¶
+FastAPIUsers instance and generate an auth router for each one of them.
+
Authentication¶
+How it works?¶
+HTTPException is raised./login and /logout. More on this in the routers documentation.Transport + Strategy = Authentication backend¶
+Transport¶
+Bearer¶
+Authorization: Bearer header.
+
+Cookie¶
+
+
+Strategy¶
+JWT¶
+
+
+Database¶
+
+
+Redis¶
+
+
+
+
Database¶
+Configuration¶
+Database adapters¶
+
+
+token (str) – Unique identifier of the token. It's generated automatically upon login by the strategy.user_id (ID) – User id. of the user associated to this token.created_at (datetime) – Date and time of creation of the token. It's used to determine if the token is expired or not.SQLAlchemy¶
+from typing import AsyncGenerator
+
+from fastapi import Depends
+from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
+from fastapi_users_db_sqlalchemy.access_token import (
+ SQLAlchemyAccessTokenDatabase,
+ SQLAlchemyBaseAccessTokenTableUUID,
+)
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ pass
+
+
+class AccessToken(SQLAlchemyBaseAccessTokenTableUUID, Base): # (1)!
+ pass
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User)
+
+
+async def get_access_token_db(
+ session: AsyncSession = Depends(get_async_session),
+): # (2)!
+ yield SQLAlchemyAccessTokenDatabase(session, AccessToken)
+
+
+AccessToken ORM model inheriting from SQLAlchemyBaseAccessTokenTableUUID.SQLAlchemyAccessTokenDatabase class. Just like the user database adapter, it expects a fresh SQLAlchemy session and the AccessToken model class we defined above.user_id foreign key is defined as UUIDSQLAlchemyBaseAccessTokenTable as base class and define your own user_id column.class AccessToken(SQLAlchemyBaseAccessTokenTable[int], Base):
+ @declared_attr
+ def user_id(cls):
+ return Column(Integer, ForeignKey("user.id", ondelete="cascade"), nullable=False)
+SQLAlchemyBaseAccessTokenTable expects a generic type to define the actual type of ID you use.Beanie¶
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+from fastapi_users_db_beanie.access_token import (
+ BeanieAccessTokenDatabase,
+ BeanieBaseAccessToken,
+)
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser):
+ pass
+
+
+class AccessToken(BeanieBaseAccessToken[PydanticObjectId]): # (1)!
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+
+
+async def get_access_token_db(): # (2)!
+ yield BeanieAccessTokenDatabase(AccessToken)
+
+
+AccessToken ODM model inheriting from BeanieBaseAccessToken. Notice that we set a generic type to define the type of the user_id reference. By default, it's a standard MongoDB ObjectID.BeanieAccessTokenDatabase class. Just like the user database adapter, it expects the AccessToken model class we defined above.Strategy¶
+import uuid
+
+from fastapi import Depends
+from fastapi_users.authentication.strategy.db import AccessTokenDatabase, DatabaseStrategy
+
+from .db import AccessToken, User
+
+
+def get_database_strategy(
+ access_token_db: AccessTokenDatabase[AccessToken] = Depends(get_access_token_db),
+) -> DatabaseStrategy:
+ return DatabaseStrategy(access_token_db, lifetime_seconds=3600)
+
+
+database (AccessTokenDatabase): A database adapter instance for AccessToken table, like we defined above.lifetime_seconds (int): The lifetime of the token in seconds.Logout¶
+
+
JWT¶
+Configuration¶
+from fastapi_users.authentication import JWTStrategy
+
+SECRET = "SECRET"
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+
+secret (Union[str, pydantic.SecretStr]): A constant secret which is used to encode the token. Use a strong passphrase and keep it secure.lifetime_seconds (Optional[int]): The lifetime of the token in seconds. Can be set to None but in this case the token will be valid forever; which may raise serious security concerns.token_audience (Optional[List[str]]): A list of valid audiences for the JWT token. Defaults to ["fastapi-users:auth"].algorithm (Optional[str]): The JWT encryption algorithm. See RFC 7519, section 8. Defaults to "HS256".public_key (Optional[Union[str, pydantic.SecretStr]]): If the JWT encryption algorithm requires a key pair instead of a simple secret, the key to decrypt the JWT may be provided here. The secret parameter will always be used to encrypt the JWT.JWTStrategy, since it doesn't require dependencies, it can be as simple as the function above.RS256 example¶
+from fastapi_users.authentication import JWTStrategy
+
+PUBLIC_KEY = """-----BEGIN PUBLIC KEY-----
+# Your RSA public key in PEM format goes here
+-----END PUBLIC KEY-----"""
+
+PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
+# Your RSA private key in PEM format goes here
+-----END RSA PRIVATE KEY-----"""
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(
+ secret=PRIVATE_KEY,
+ lifetime_seconds=3600,
+ algorithm="RS256",
+ public_key=PUBLIC_KEY,
+ )
+Logout¶
+
+
Redis¶
+Installation¶
+Configuration¶
+import redis.asyncio
+from fastapi_users.authentication import RedisStrategy
+
+redis = redis.asyncio.from_url("redis://localhost:6379", decode_responses=True)
+
+def get_redis_strategy() -> RedisStrategy:
+ return RedisStrategy(redis, lifetime_seconds=3600)
+
+
+redis (redis.asyncio.Redis): An instance of redis.asyncio.Redis. Note that the decode_responses flag set to True is necessary.lifetime_seconds (Optional[int]): The lifetime of the token in seconds. Defaults to None, which means the token doesn't expire.key_prefix (str): The prefix used to set the key in the Redis stored. Defaults to fastapi_users_token:.Logout¶
+
+
Bearer¶
+Authorization header of the HTTP request with the Bearer scheme. It's particularly suited for pure API interaction or mobile apps.Configuration¶
+from fastapi_users.authentication import BearerTransport
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+
+tokenUrl (str): The exact path of your login endpoint. It'll allow the interactive documentation to automatically discover it and get a working Authorize button. In most cases, you'll probably need a relative path, not absolute. You can read more details about this in the FastAPI documentation.Login¶
+200 OK
+
+Logout¶
+Authentication¶
+Bearer authentication with a valid token corresponding to your strategy.
+
Cookie¶
+Configuration¶
+from fastapi_users.authentication import CookieTransport
+
+cookie_transport = CookieTransport(cookie_max_age=3600)
+
+
+cookie_name (fastapiusersauth): Name of the cookie.cookie_max_age (Optional[int]): The lifetime of the cookie in seconds. None by default, which means it's a session cookie.cookie_path (/): Cookie path.cookie_domain (None): Cookie domain.cookie_secure (True): Whether to only send the cookie to the server via SSL request.cookie_httponly (True): Whether to prevent access to the cookie via JavaScript.cookie_samesite (lax): A string that specifies the samesite strategy for the cookie. Valid values are lax, strict and none. Defaults to lax.Login¶
+set-cookie header upon successful login:200 OK
+
+Logout¶
+200 OK
+
+Authentication¶
+
+
Beanie¶
+Setup database connection and collection¶
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+Create the User model¶
+User model.import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+User table. You can of course add you own fields there to fit to your needs!id field:import uuid
+
+from pydantic import Field
+
+
+class User(BeanieBaseUser[uuid.UUID]):
+ id: uuid.UUID = Field(default_factory=uuid.uuid4)
+BeanieBaseUser expects a generic type to define the actual type of ID you use.id and email.Create the database adapter¶
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+User model we defined above.Initialize Beanie¶
+from beanie import init_beanie
+
+
+@app.on_event("startup")
+async def on_startup():
+ await init_beanie(
+ database=db, # (1)!
+ document_models=[
+ User, # (2)!
+ ],
+ )
+
+
+
+
+
+
+
+
+ db Motor database instance we defined above.User model we defined above. Don't forget to also add your very own models!
+
SQLAlchemy¶
+Asynchronous driver¶
+
+
+pip install asyncpgpip install aiosqliteDB_URLs are:
+
+engine = create_engine('postgresql+asyncpg://user:password@host:port/name')engine = create_engine('sqlite+aiosqlite:///name.db')Create the User model¶
+User model.from typing import AsyncGenerator
+
+from fastapi import Depends
+from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ pass
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User)
+User table. You can of course add you own fields there to fit to your needs!SQLAlchemyBaseUserTable as base class and define your own id column.SQLAlchemyBaseUserTable expects a generic type to define the actual type of ID you use.Implement a function to create the tables¶
+from typing import AsyncGenerator
+
+from fastapi import Depends
+from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ pass
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User)
+Create the database adapter dependency¶
+from typing import AsyncGenerator
+
+from fastapi import Depends
+from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ pass
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User)
+get_async_session dependency returning us a fresh SQLAlchemy session to interact with the database.get_user_db dependency to generate our adapter. Notice that we pass it two things:
+
+
+
+
+
+
+
+ session instance we just injected.User class, which is the actual SQLAlchemy model.
+
Full example¶
+SQLAlchemy¶
+
+from fastapi import Depends, FastAPI
+
+from app.db import User, create_db_and_tables
+from app.schemas import UserCreate, UserRead, UserUpdate
+from app.users import auth_backend, current_active_user, fastapi_users
+
+app = FastAPI()
+
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+
+
+@app.get("/authenticated-route")
+async def authenticated_route(user: User = Depends(current_active_user)):
+ return {"message": f"Hello {user.email}!"}
+
+
+@app.on_event("startup")
+async def on_startup():
+ # Not needed if you setup a migration system like Alembic
+ await create_db_and_tables()
+from typing import AsyncGenerator
+
+from fastapi import Depends
+from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ pass
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User)
+import uuid
+from typing import Optional
+
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
+from fastapi_users.authentication import (
+ AuthenticationBackend,
+ BearerTransport,
+ JWTStrategy,
+)
+from fastapi_users.db import SQLAlchemyUserDatabase
+
+from app.db import User, get_user_db
+
+SECRET = "SECRET"
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
+ yield UserManager(user_db)
+
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
+
+current_active_user = fastapi_users.current_user(active=True)
+Beanie¶
+
+from beanie import init_beanie
+from fastapi import Depends, FastAPI
+
+from app.db import User, db
+from app.schemas import UserCreate, UserRead, UserUpdate
+from app.users import auth_backend, current_active_user, fastapi_users
+
+app = FastAPI()
+
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+
+
+@app.get("/authenticated-route")
+async def authenticated_route(user: User = Depends(current_active_user)):
+ return {"message": f"Hello {user.email}!"}
+
+
+@app.on_event("startup")
+async def on_startup():
+ await init_beanie(
+ database=db,
+ document_models=[
+ User,
+ ],
+ )
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+from typing import Optional
+
+from beanie import PydanticObjectId
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, FastAPIUsers
+from fastapi_users.authentication import (
+ AuthenticationBackend,
+ BearerTransport,
+ JWTStrategy,
+)
+from fastapi_users.db import BeanieUserDatabase, ObjectIDIDMixin
+
+from app.db import User, get_user_db
+
+SECRET = "SECRET"
+
+
+class UserManager(ObjectIDIDMixin, BaseUserManager[User, PydanticObjectId]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db: BeanieUserDatabase = Depends(get_user_db)):
+ yield UserManager(user_db)
+
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+fastapi_users = FastAPIUsers[User, PydanticObjectId](get_user_manager, [auth_backend])
+
+current_active_user = fastapi_users.current_user(active=True)
+What now?¶
+
+
OAuth2¶
+Installation¶
+Configuration¶
+Instantiate an OAuth2 client¶
+from httpx_oauth.clients.google import GoogleOAuth2
+
+google_oauth_client = GoogleOAuth2("CLIENT_ID", "CLIENT_SECRET")
+Setup the database adapter¶
+SQLAlchemy¶
+from typing import AsyncGenerator, List
+
+from fastapi import Depends
+from fastapi_users.db import (
+ SQLAlchemyBaseOAuthAccountTableUUID,
+ SQLAlchemyBaseUserTableUUID,
+ SQLAlchemyUserDatabase,
+)
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, relationship, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):
+ pass
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ oauth_accounts: List[OAuthAccount] = relationship("OAuthAccount", lazy="joined")
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User, OAuthAccount)
+relationship on the UserTable so that SQLAlchemy can properly retrieve the OAuth accounts of the user.SQLAlchemyBaseOAuthAccountTable as base class and define your own id and user_id column.class OAuthAccount(SQLAlchemyBaseOAuthAccountTable[int], Base):
+ id = Column(Integer, primary_key=True)
+
+ @declared_attr
+ def user_id(cls):
+ return Column(Integer, ForeignKey("user.id", ondelete="cascade"), nullable=False)
+SQLAlchemyBaseOAuthAccountTable expects a generic type to define the actual type of ID you use.Beanie¶
+from typing import List
+
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BaseOAuthAccount, BeanieBaseUser, BeanieUserDatabase
+from pydantic import Field
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class OAuthAccount(BaseOAuthAccount):
+ pass
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ oauth_accounts: List[OAuthAccount] = Field(default_factory=list)
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User, OAuthAccount)
+OAuthAccount is not a Beanie document but a Pydantic model that we'll embed inside the User document, through the oauth_accounts array.Generate routers¶
+FastAPIUsers instance, you can make it generate a single OAuth router for a given client and authentication backend.app.include_router(
+ fastapi_users.get_oauth_router(google_oauth_client, auth_backend, "SECRET"),
+ prefix="/auth/google",
+ tags=["auth"],
+)
+Existing account association¶
+associate_by_email flag:app.include_router(
+ fastapi_users.get_oauth_router(
+ google_oauth_client,
+ auth_backend,
+ "SECRET",
+ associate_by_email=True,
+ ),
+ prefix="/auth/google",
+ tags=["auth"],
+)
+
+
+lancelot@camelot.bt.lancelot@camelot.bt.Association router for authenticated users¶
+app.include_router(
+ fastapi_users.get_oauth_associate_router(google_oauth_client, UserRead, "SECRET"),
+ prefix="/auth/associate/google",
+ tags=["auth"],
+)
+UserRead Pydantic schema.Full example¶
+SQLAlchemy¶
+
+from fastapi import Depends, FastAPI
+
+from app.db import User, create_db_and_tables
+from app.schemas import UserCreate, UserRead, UserUpdate
+from app.users import (
+ SECRET,
+ auth_backend,
+ current_active_user,
+ fastapi_users,
+ google_oauth_client,
+)
+
+app = FastAPI()
+
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+app.include_router(
+ fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET),
+ prefix="/auth/google",
+ tags=["auth"],
+)
+
+
+@app.get("/authenticated-route")
+async def authenticated_route(user: User = Depends(current_active_user)):
+ return {"message": f"Hello {user.email}!"}
+
+
+@app.on_event("startup")
+async def on_startup():
+ # Not needed if you setup a migration system like Alembic
+ await create_db_and_tables()
+from typing import AsyncGenerator, List
+
+from fastapi import Depends
+from fastapi_users.db import (
+ SQLAlchemyBaseOAuthAccountTableUUID,
+ SQLAlchemyBaseUserTableUUID,
+ SQLAlchemyUserDatabase,
+)
+from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
+from sqlalchemy.orm import DeclarativeMeta, declarative_base, relationship, sessionmaker
+
+DATABASE_URL = "sqlite+aiosqlite:///./test.db"
+Base: DeclarativeMeta = declarative_base()
+
+
+class OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):
+ pass
+
+
+class User(SQLAlchemyBaseUserTableUUID, Base):
+ oauth_accounts: List[OAuthAccount] = relationship("OAuthAccount", lazy="joined")
+
+
+engine = create_async_engine(DATABASE_URL)
+async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
+
+
+async def create_db_and_tables():
+ async with engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+
+
+async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
+ async with async_session_maker() as session:
+ yield session
+
+
+async def get_user_db(session: AsyncSession = Depends(get_async_session)):
+ yield SQLAlchemyUserDatabase(session, User, OAuthAccount)
+import os
+import uuid
+from typing import Optional
+
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
+from fastapi_users.authentication import (
+ AuthenticationBackend,
+ BearerTransport,
+ JWTStrategy,
+)
+from fastapi_users.db import SQLAlchemyUserDatabase
+from httpx_oauth.clients.google import GoogleOAuth2
+
+from app.db import User, get_user_db
+
+SECRET = "SECRET"
+
+google_oauth_client = GoogleOAuth2(
+ os.getenv("GOOGLE_OAUTH_CLIENT_ID", ""),
+ os.getenv("GOOGLE_OAUTH_CLIENT_SECRET", ""),
+)
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
+ yield UserManager(user_db)
+
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
+
+current_active_user = fastapi_users.current_user(active=True)
+Beanie¶
+
+from beanie import init_beanie
+from fastapi import Depends, FastAPI
+
+from app.db import User, db
+from app.schemas import UserCreate, UserRead, UserUpdate
+from app.users import (
+ SECRET,
+ auth_backend,
+ current_active_user,
+ fastapi_users,
+ google_oauth_client,
+)
+
+app = FastAPI()
+
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+app.include_router(
+ fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET),
+ prefix="/auth/google",
+ tags=["auth"],
+)
+
+
+@app.get("/authenticated-route")
+async def authenticated_route(user: User = Depends(current_active_user)):
+ return {"message": f"Hello {user.email}!"}
+
+
+@app.on_event("startup")
+async def on_startup():
+ await init_beanie(
+ database=db,
+ document_models=[
+ User,
+ ],
+ )
+from typing import List
+
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BaseOAuthAccount, BeanieBaseUser, BeanieUserDatabase
+from pydantic import Field
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class OAuthAccount(BaseOAuthAccount):
+ pass
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ oauth_accounts: List[OAuthAccount] = Field(default_factory=list)
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User, OAuthAccount)
+import os
+from typing import Optional
+
+from beanie import PydanticObjectId
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, FastAPIUsers
+from fastapi_users.authentication import (
+ AuthenticationBackend,
+ BearerTransport,
+ JWTStrategy,
+)
+from fastapi_users.db import BeanieUserDatabase, ObjectIDIDMixin
+from httpx_oauth.clients.google import GoogleOAuth2
+
+from app.db import User, get_user_db
+
+SECRET = "SECRET"
+
+google_oauth_client = GoogleOAuth2(
+ os.getenv("GOOGLE_OAUTH_CLIENT_ID", ""),
+ os.getenv("GOOGLE_OAUTH_CLIENT_SECRET", ""),
+)
+
+
+class UserManager(ObjectIDIDMixin, BaseUserManager[User, PydanticObjectId]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db: BeanieUserDatabase = Depends(get_user_db)):
+ yield UserManager(user_db)
+
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+fastapi_users = FastAPIUsers[User, PydanticObjectId](get_user_manager, [auth_backend])
+
+current_active_user = fastapi_users.current_user(active=True)
+
+
Overview¶
+
+flowchart TB
+ FASTAPI_USERS{FastAPIUsers}
+ USER_MANAGER{UserManager}
+ USER_MODEL{User model}
+ DATABASE_DEPENDENCY[[get_user_db]]
+ USER_MANAGER_DEPENDENCY[[get_user_manager]]
+ CURRENT_USER[[current_user]]
+ subgraph SCHEMAS[Schemas]
+ USER[User]
+ USER_CREATE[UserCreate]
+ USER_UPDATE[UserUpdate]
+ end
+ subgraph DATABASE[Database adapters]
+ SQLALCHEMY[SQLAlchemy]
+ BEANIE[Beanie]
+ end
+ subgraph ROUTERS[Routers]
+ AUTH[[get_auth_router]]
+ OAUTH[[get_oauth_router]]
+ OAUTH_ASSOCIATE[[get_oauth_associate_router]]
+ REGISTER[[get_register_router]]
+ VERIFY[[get_verify_router]]
+ RESET[[get_reset_password_router]]
+ USERS[[get_users_router]]
+ end
+ subgraph AUTH_BACKENDS[Authentication]
+ subgraph TRANSPORTS[Transports]
+ COOKIE[CookieTransport]
+ BEARER[BearerTransport]
+ end
+ subgraph STRATEGIES[Strategies]
+ DB[DatabaseStrategy]
+ JWT[JWTStrategy]
+ REDIS[RedisStrategy]
+ end
+ AUTH_BACKEND{AuthenticationBackend}
+ end
+ DATABASE --> DATABASE_DEPENDENCY
+ USER_MODEL --> DATABASE_DEPENDENCY
+ DATABASE_DEPENDENCY --> USER_MANAGER
+
+ USER_MANAGER --> USER_MANAGER_DEPENDENCY
+ USER_MANAGER_DEPENDENCY --> FASTAPI_USERS
+
+ FASTAPI_USERS --> ROUTERS
+
+ TRANSPORTS --> AUTH_BACKEND
+ STRATEGIES --> AUTH_BACKEND
+
+ AUTH_BACKEND --> ROUTERS
+ AUTH_BACKEND --> FASTAPI_USERS
+
+ FASTAPI_USERS --> CURRENT_USER
+
+ SCHEMAS --> ROUTERSUser model and database adapters¶
+Authentication backends¶
+
+UserManager¶UserManager object bears most of the logic of FastAPI Users: registration, verification, password reset... We provide a BaseUserManager with this common logic; which you should overload to define how to validate passwords or handle events.UserManager object should be provided through a FastAPI dependency, get_user_manager.Schemas¶
+
+FastAPIUsers and routers¶FastAPIUsers object is the main class from which you'll be able to generate routers for classic routes like registration or login, but also get the current_user dependency factory to inject the authenticated user in your own routes.
+
Password hash¶
+Customize
+CryptContext¶CryptContext object of Passlib.PasswordHelper class and pass it your CryptContext. The example below shows you how you can create a CryptContext to add support for the Argon2 algorithm while deprecating BCrypt.from fastapi_users.password import PasswordHelper
+from passlib.context import CryptContext
+
+context = CryptContext(schemes=["argon2", "bcrypt"], deprecated="auto")
+password_helper = PasswordHelper(context)
+password_helper variable while instantiating your UserManager:async def get_user_manager(user_db=Depends(get_user_db)):
+ yield UserManager(user_db, password_helper)
+Full customization¶
+PasswordHelper class as long as it implements the PasswordHelperProtocol and its methods.from typing import Tuple
+
+from fastapi_users.password import PasswordHelperProtocol
+
+class PasswordHelper(PasswordHelperProtocol):
+ def verify_and_update(
+ self, plain_password: str, hashed_password: str
+ ) -> Tuple[bool, str]:
+ ...
+
+ def hash(self, password: str) -> str:
+ ...
+
+ def generate(self) -> str:
+ ...
+
+
Auth router¶
+/login and /logout routes for a given authentication backend.Setup¶
+import uuid
+
+from fastapi import FastAPI
+from fastapi_users import FastAPIUsers
+
+from .db import User
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+app = FastAPI()
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend),
+ prefix="/auth/jwt",
+ tags=["auth"],
+)
+Optional: user verification¶
+is_verified property set to True) to allow login. You have to set the requires_verification parameter to True on the router instantiation method:
+
Routers¶
+FastAPIUsers object that will wire the user manager, the authentication classes and let us generate the actual API routes.Configure
+FastAPIUsers¶FastAPIUsers object with the elements we defined before. More precisely:
+
+get_user_manager: Dependency callable getter to inject the
+ user manager class instance. See UserManager.auth_backends: List of authentication backends. See Authentication.import uuid
+
+from fastapi_users import FastAPIUsers
+
+from .db import User
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+
+User, which is the user model we defined in the database partAvailable routers¶
+
+
+/login and /logout routes for a given authentication backend./register routes to allow a user to create a new account./forgot-password and /reset-password routes to allow a user to reset its password./request-verify-token and /verify routes to manage user e-mail verification.
+
Register routes¶
+/register route to allow a user to create a new account.Setup¶
+import uuid
+
+from fastapi import FastAPI
+from fastapi_users import FastAPIUsers
+
+from .db import User
+from .schemas import UserCreate, UserRead
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+app = FastAPI()
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+
+
Reset password router¶
+/forgot-password (the user asks for a token to reset its password) and /reset-password (the user changes its password given the token) routes.Setup¶
+import uuid
+
+from fastapi import FastAPI
+from fastapi_users import FastAPIUsers
+
+from .db import User
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+app = FastAPI()
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+
+
Users router¶
+Setup¶
+import uuid
+
+from fastapi import FastAPI
+from fastapi_users import FastAPIUsers
+
+from .db import User
+from .schemas import UserRead, UserUpdate
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+app = FastAPI()
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+Optional: user verification¶
+is_verified property set to True) to access those routes. You have to set the requires_verification parameter to True on the router instantiation method:
+
Verify router¶
+Setup¶
+import uuid
+
+from fastapi import FastAPI
+from fastapi_users import FastAPIUsers
+
+from .db import User
+from .schemas import UserRead
+
+fastapi_users = FastAPIUsers[User, uuid.UUID](
+ get_user_manager,
+ [auth_backend],
+)
+
+app = FastAPI()
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+
+
Schemas¶
+User model, which is an object that actually interacts with the database. Those schemas on the other hand are here to validate data and serialize correct it in the API.
+
+id (ID) – Unique identifier of the user. It matches the type of your ID, like UUID or integer.email (str) – Email of the user. Validated by email-validator.is_active (bool) – Whether or not the user is active. If not, login and forgot password requests will be denied. Defaults to True.is_verified (bool) – Whether or not the user is verified. Optional but helpful with the verify router logic. Defaults to False.is_superuser (bool) – Whether or not the user is a superuser. Useful to implement administration logic. Defaults to False.Define your schemas¶
+
+
+BaseUser, which provides the basic fields and validation;BaseCreateUser, dedicated to user registration, which consists of compulsory email and password fields;BaseUpdateUser, dedicated to user profile update, which adds an optional password field;import uuid
+
+from fastapi_users import schemas
+
+
+class UserRead(schemas.BaseUser[uuid.UUID]):
+ pass
+
+
+class UserCreate(schemas.BaseUserCreate):
+ pass
+
+
+class UserUpdate(schemas.BaseUserUpdate):
+ pass
+BaseUser class. It should correspond to the type of ID you use on your model. Here, we chose UUID, but it can be anything, like an integer or a MongoDB ObjectID.Adding your own fields¶
+first_name, and an optional date property, birthdate.import datetime
+import uuid
+
+from fastapi_users import schemas
+
+
+class UserRead(schemas.BaseUser[uuid.UUID]):
+ first_name: str
+ birthdate: Optional[datetime.date]
+
+
+class UserCreate(schemas.BaseUserCreate):
+ first_name: str
+ birthdate: Optional[datetime.date]
+
+
+class UserUpdate(schemas.BaseUserUpdate):
+ first_name: Optional[str]
+ birthdate: Optional[datetime.date]
+User model you defined earlier for your specific database will be the central object that will actually store the data. Therefore, you need to define the very same fields in it so the data can be actually stored.
+
UserManager¶
+UserManager class is the core logic of FastAPI Users. We provide the BaseUserManager class which you should extend to set some parameters and define logic, for example when a user just registered or forgot its password.Create your
+UserManager class¶UserManager class to set various parameters.import uuid
+from typing import Optional
+
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, UUIDIDMixin
+
+from .db import User, get_user_db
+
+SECRET = "SECRET"
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db=Depends(get_user_db)):
+ yield UserManager(user_db)
+
+
+User, which is the user model we defined in the database partThe ID parser mixin¶
+UUIDIDMixin in the example above. It implements the parse_id method, ensuring UUID are valid and correctly parsed.
+
+UUIDIDMixin, for UUID ID.IntegerIDMixin, for integer ID.ObjectIDIDMixin (provided by fastapi_users_db_beanie), for MongoDB ObjectID.UserManager inheritance. Because of the Method-Resolution-Order (MRO) of Python, the left-most element takes precedence.parse_id method on your UserManager class:from fastapi_users import BaseUserManager, InvalidID
+
+
+class UserManager(BaseUserManager[User, MyCustomID]):
+ def parse_id(self, value: Any) -> MyCustomID:
+ try:
+ return MyCustomID(value)
+ except ValueError as e:
+ raise InvalidID() from e # (1)!
+
+
+InvalidID exception.Create
+get_user_manager dependency¶UserManager class will be injected at runtime using a FastAPI dependency. This way, you can run it in a database session or swap it with a mock during testing.import uuid
+from typing import Optional
+
+from fastapi import Depends, Request
+from fastapi_users import BaseUserManager, UUIDIDMixin
+
+from .db import User, get_user_db
+
+SECRET = "SECRET"
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+
+async def get_user_manager(user_db=Depends(get_user_db)):
+ yield UserManager(user_db)
+get_user_db dependency we defined earlier to inject the database instance.Customize attributes and methods¶
+Attributes¶
+
+
+reset_password_token_secret: Secret to encode reset password token. Use a strong passphrase and keep it secure.reset_password_token_lifetime_seconds: Lifetime of reset password token. Defaults to 3600.reset_password_token_audience: JWT audience of reset password token. Defaults to fastapi-users:reset.verification_token_secret: Secret to encode verification token. Use a strong passphrase and keep it secure.verification_token_lifetime_seconds: Lifetime of verification token. Defaults to 3600.verification_token_audience: JWT audience of verification token. Defaults to fastapi-users:verify.Methods¶
+
+validate_password¶
+
+password (str): the password to validate.user (Union[UserCreate, User]): user model which we are currently validating the password. Useful if you want to check that the password doesn't contain the name or the birthdate of the user for example.None if the password is valid or raise InvalidPasswordException if not. This exception expects an argument reason telling why the password is invalid. It'll be part of the error response.from fastapi_users import BaseUserManager, InvalidPasswordException, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def validate_password(
+ self,
+ password: str,
+ user: Union[UserCreate, User],
+ ) -> None:
+ if len(password) < 8:
+ raise InvalidPasswordException(
+ reason="Password should be at least 8 characters"
+ )
+ if user.email in password:
+ raise InvalidPasswordException(
+ reason="Password should not contain e-mail"
+ )
+
+on_after_register¶
+
+user (User): the registered user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+on_after_update¶
+
+user (User): the updated user.update_dict (Dict[str, Any]): dictionary with the updated user fields.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_update(
+ self,
+ user: User,
+ update_dict: Dict[str, Any],
+ request: Optional[Request] = None,
+ ):
+ print(f"User {user.id} has been updated with {update_dict}.")
+
+on_after_login¶
+
+user (User): the updated user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_login(
+ self,
+ user: User,
+ request: Optional[Request] = None,
+ ):
+ print(f"User {user.id} logged in.")
+
+on_after_request_verify¶
+
+user (User): the user to verify.token (str): the verification token.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+
+on_after_verify¶
+
+user (User): the verified user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_verify(
+ self, user: User, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has been verified")
+
+on_after_forgot_password¶
+
+user (User): the user that forgot its password.token (str): the forgot password tokenrequest (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+on_after_reset_password¶
+
+user (User): the user that reset its password.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_after_reset_password(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has reset their password.")
+
+on_before_delete¶
+
+user (User): the user to be deleted.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.from fastapi_users import BaseUserManager, UUIDIDMixin
+
+
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ # ...
+ async def on_before_delete(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} is going to be deleted")
+
+on_after_delete¶
+
+user (User): the user to be deleted.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
+
Create a user programmatically¶
+UserManager class and all other dependent objects manually.1. Define dependencies as context managers¶
+yield keyword. FastAPI knows very well to handle them inside its dependency injection system. For example, here is the definition of the get_user_manager dependency:async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):
+ yield UserManager(user_db)
+for loop, which would be a bit unnatural in this context since we have only one value to get, the user manager instance. To avoid this, we'll transform them into context managers, so we can call them using the with..as syntax. Fortunately, the standard library provides tools to automatically transform generators into context managers.contextlib.asynccontextmanager:import contextlib
+
+from app.db import get_async_session, get_user_db
+from app.schemas import UserCreate
+from app.users import get_user_manager
+from fastapi_users.exceptions import UserAlreadyExists
+
+get_async_session_context = contextlib.asynccontextmanager(get_async_session)
+get_user_db_context = contextlib.asynccontextmanager(get_user_db)
+get_user_manager_context = contextlib.asynccontextmanager(get_user_manager)
+
+
+async def create_user(email: str, password: str, is_superuser: bool = False):
+ try:
+ async with get_async_session_context() as session:
+ async with get_user_db_context(session) as user_db:
+ async with get_user_manager_context(user_db) as user_manager:
+ user = await user_manager.create(
+ UserCreate(
+ email=email, password=password, is_superuser=is_superuser
+ )
+ )
+ print(f"User created {user}")
+ except UserAlreadyExists:
+ print(f"User {email} already exists")
+2. Write a function¶
+import contextlib
+
+from app.db import get_async_session, get_user_db
+from app.schemas import UserCreate
+from app.users import get_user_manager
+from fastapi_users.exceptions import UserAlreadyExists
+
+get_async_session_context = contextlib.asynccontextmanager(get_async_session)
+get_user_db_context = contextlib.asynccontextmanager(get_user_db)
+get_user_manager_context = contextlib.asynccontextmanager(get_user_manager)
+
+
+async def create_user(email: str, password: str, is_superuser: bool = False):
+ try:
+ async with get_async_session_context() as session:
+ async with get_user_db_context(session) as user_db:
+ async with get_user_manager_context(user_db) as user_manager:
+ user = await user_manager.create(
+ UserCreate(
+ email=email, password=password, is_superuser=is_superuser
+ )
+ )
+ print(f"User created {user}")
+ except UserAlreadyExists:
+ print(f"User {email} already exists")
+3. Use it¶
+
+
FastAPI Users¶
+
+
+
+Features¶
+
+
+
+
+
+
+In a hurry? Discover Fief, the open-source authentication platform¶
+
+
+
+Contributors and sponsors ✨☕️¶
+Development¶
+Setup environment¶
+Run unit tests¶
+Format the code¶
+isort and black formatting:Serve the documentation¶
+License¶
+
+
Installation¶
+With SQLAlchemy support¶
+
+With Beanie support¶
+
+With Redis authentication backend support¶
+With OAuth2 support¶
+
+
+
0.8.x ➡️ 1.x.x¶
+Id. are UUID¶
+In Python code¶
+# Before
+assert "d35d213e-f3d8-4f08-954a-7e0d1bea286f" == user.id
+
+# Now
+assert "d35d213e-f3d8-4f08-954a-7e0d1bea286f" == str(user.id)
+UUID4 type instead of str:from pydantic import BaseModel, UUID4
+
+# Before
+class Model(BaseModel):
+ user_id: str
+
+# After
+class Model(BaseModel):
+ user_id: UUID4
+MongoDB¶
+standard UUID representation when instantiating the MongoDB client:DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+pythonLegacy but new applications should consider setting this to standard for cross language compatibility. Read more about this.In database¶
+PostgreSQL¶
+uuid-ossp extension:
+
+ALTER TABLE "user" ADD uuid_id UUID;
+UPDATE "user" SET uuid_id = uuid(id);
+ALTER TABLE "user" DROP id;
+ALTER TABLE "user" ADD PRIMARY KEY (uuid_id);
+ALTER TABLE "user" RENAME COLUMN uuid_id TO id;
+MySQL¶
+CHAR(36) type:MongoDB¶
+Mongo shell¶
+forEach iterator to convert the id. for each document:db.getCollection('users').find().forEach(function(user) {
+ var uuid = UUID(user.id);
+ db.getCollection('users').update({_id: user._id}, [{$set: {id: uuid}}]);
+});
+Python¶
+import uuid
+
+import motor.motor_asyncio
+
+
+async def migrate_uuid():
+ client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+ )
+ db = client["database_name"]
+ users = db["users"]
+
+ async for user in users.find({}):
+ await users.update_one(
+ {"_id": user["_id"]},
+ {"$set": {"id": uuid.UUID(user["id"])}},
+ )
+Splitted routers¶
+Before¶
+jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)
+
+app = FastAPI()
+fastapi_users = FastAPIUsers(
+ user_db, [jwt_authentication], User, UserCreate, UserUpdate, UserDB,
+)
+app.include_router(fastapi_users.router, prefix="/users", tags=["users"])
+
+
+@fastapi_users.on_after_register()
+def on_after_register(user: User, request: Request):
+ print(f"User {user.id} has registered.")
+
+
+@fastapi_users.on_after_forgot_password()
+def on_after_forgot_password(user: User, token: str, request: Request):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+After¶
+def on_after_register(user: UserDB, request: Request):
+ print(f"User {user.id} has registered.")
+
+
+def on_after_forgot_password(user: UserDB, token: str, request: Request):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+
+jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)
+
+app = FastAPI()
+fastapi_users = FastAPIUsers(
+ user_db, [jwt_authentication], User, UserCreate, UserUpdate, UserDB,
+)
+app.include_router(
+ fastapi_users.get_auth_router(jwt_authentication), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(on_after_register), prefix="/auth", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(
+ SECRET, after_forgot_password=on_after_forgot_password
+ ),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"])
+
+
+
+
+
+
+
+
+ FastAPIUsers takes two arguments less (reset_password_token_secret and reset_password_token_lifetime_seconds)./login//logout are now your responsibility to include for each backend. The path will change (before /login/jwt, after /jwt/login).
+
1.x.x ➡️ 2.x.x¶
+JWT authentication backend¶
+{
+ "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI"
+}
+{
+ "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI",
+ "token_type": "bearer"
+}
+
+
2.x.x ➡️ 3.x.x¶
+Emails are now case-insensitive¶
+king.arthur@camelot.bt and King.Arthur@camelot.bt were considered as two different users. This behaviour was a bit confusing and not consistent with 99% of web services out there.King.Arthur@camelot.bt, it will be stored exactly like this in the database (with casing) ; but he will be able to login as king.arthur@camelot.bt.
+
3.x.x ➡️ 4.x.x¶
+
+expires_at property in OAuthAccount is now optional¶expires_at property in OAuthAccount model was mandatory. It was causing issues with some services that don't have such expiration property.
+
4.x.x ➡️ 5.x.x¶
+New property
+is_verified in User model.¶is_verified property has been added to the User model.
+
6.x.x ➡️ 7.x.x¶
+
+
+current_user factory instead. [Documentation]UserUpdate model shouldn't inherit from the base User class. If you have custom fields, you should repeat them in this model. [Documentation]
+
+
+
+
+
+
+
+
+ import statements remain unchanged.
+
7.x.x ➡️ 8.x.x¶
+UserManager class and a associated dependency to create an instance of this class.Event handlers should live in the
+UserManager¶on_after_register or on_after_forgot_password were defined in their own functions that were passed as arguments of router generators.UserManager class.UserManager documentation.Password validation should live in the
+UserManager¶FastAPIUsers.UserManager class.UserManager documentation.Verify token secret and lifetime parameters are attributes of
+UserManager¶get_verify_router.UserManager class.UserManager documentation.Reset password token secret and lifetime parameters are attributes of
+UserManager¶get_verify_router.UserManager class.UserManager documentation.Database adapter should be provided in a dependency¶
+FastAPIUsers now expect a
+get_user_manager dependency¶FastAPIUsers.get_user_manager dependency returning an instance of your UserManager class. This dependency will be dependent of the database adapter dependency.UserManager documentation and FastAPIUsers documentationLost?¶
+
+
8.x.x ➡️ 9.x.x¶
+Convert the authentication backend¶
+I used JWTAuthentication¶
+from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy
+
+SECRET = "SECRET"
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+auth_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+name anymore: you need to provide it yourself for each of your backends.I used CookieAuthentication¶
+from fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy
+
+SECRET = "SECRET"
+
+cookie_transport = CookieTransport(cookie_max_age=3600)
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+auth_backend = AuthenticationBackend(
+ name="cookie",
+ transport=cookie_transport,
+ get_strategy=get_jwt_strategy,
+)
+name anymore: you need to provide it yourself for each of your backends.OAuth: one router for each backend¶
+
+authentication_backend is not needed on /authorize¶/authorize.Lost?¶
+
+
9.x.x ➡️ 10.x.x¶
+current_user dependency would return you an instance of UserDB, a Pydantic model. This proved to be quite problematic with some ORM if you ever needed to retrieve relationship data or make specific requests.User models and database adapter¶
+SQLAlchemy ORM¶
+fastapi-users[sqlalchemy].UserTable to User: it's not a compulsory change, but since there is no risk of confusion with Pydantic models anymore, it's probably a more idiomatic naming.SQLAlchemyUserDatabase adapter now only expects this User model. UserDB is removed.MongoDB¶
+import os
+
+import motor.motor_asyncio
+from fastapi_users.db import MongoDBUserDatabase
+
+from app.models import UserDB
+
+DATABASE_URL = os.environ["DATABASE_URL"]
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+collection = db["users"]
+
+
+async def get_user_db():
+ yield MongoDBUserDatabase(UserDB, collection)
+import motor.motor_asyncio
+from beanie import PydanticObjectId
+from fastapi_users.db import BeanieBaseUser, BeanieUserDatabase
+
+DATABASE_URL = "mongodb://localhost:27017"
+client = motor.motor_asyncio.AsyncIOMotorClient(
+ DATABASE_URL, uuidRepresentation="standard"
+)
+db = client["database_name"]
+
+
+class User(BeanieBaseUser[PydanticObjectId]):
+ pass
+
+
+async def get_user_db():
+ yield BeanieUserDatabase(User)
+id field:from beanie import init_beanie
+
+
+@app.on_event("startup")
+async def on_startup():
+ await init_beanie(
+ database=db,
+ document_models=[
+ User,
+ ],
+ )
+Tortoise ORM and ormar¶
+
+UserManager¶UserManager class. In particular, it now needs a parse_id method that can be provided through built-in mixins.user_db_model class property is removed.class UserManager(BaseUserManager[UserCreate, UserDB]):
+ user_db_model = UserDB
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: UserDB, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: UserDB, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: UserDB, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
+ reset_password_token_secret = SECRET
+ verification_token_secret = SECRET
+
+ async def on_after_register(self, user: User, request: Optional[Request] = None):
+ print(f"User {user.id} has registered.")
+
+ async def on_after_forgot_password(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"User {user.id} has forgot their password. Reset token: {token}")
+
+ async def on_after_request_verify(
+ self, user: User, token: str, request: Optional[Request] = None
+ ):
+ print(f"Verification requested for user {user.id}. Verification token: {token}")
+Pydantic models¶
+UserDB has been removed in favor of native models.User to UserRead: it's not a compulsory change, but since there is a risk of confusion with the native model, it's highly recommended.BaseUser schema now accepts a generic type to specify the type of ID you use.FastAPI Users and routers¶
+FastAPIUsers class:get_register_router, get_verify_router and get_users_router.app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(fastapi_users.get_register_router(), prefix="/auth", tags=["auth"])
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"])
+app.include_router(
+ fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
+)
+app.include_router(
+ fastapi_users.get_register_router(UserRead, UserCreate),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_reset_password_router(),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_verify_router(UserRead),
+ prefix="/auth",
+ tags=["auth"],
+)
+app.include_router(
+ fastapi_users.get_users_router(UserRead, UserUpdate),
+ prefix="/users",
+ tags=["users"],
+)
+Lost?¶
+
"},{"location":"#in-a-hurry-discover-fief-the-open-source-authentication-platform","title":"In a hurry? Discover Fief, the open-source authentication platform","text":"
"},{"location":"#format-the-code","title":"Format the code","text":"hatch run test\nisort and black formatting:
"},{"location":"#serve-the-documentation","title":"Serve the documentation","text":"hatch run lint\nhatch run docs\n
"},{"location":"installation/#with-beanie-support","title":"With Beanie support","text":"pip install 'fastapi-users[sqlalchemy]'\n
"},{"location":"installation/#with-redis-authentication-backend-support","title":"With Redis authentication backend support","text":"pip install 'fastapi-users[beanie]'\nfastapi\nfastapi-users[sqlalchemy]\nuvicorn[standard]\naiosqlite\nimport uvicorn\nif __name__ == \"__main__\":\nuvicorn.run(\"app.app:app\", host=\"0.0.0.0\", log_level=\"info\")\nfrom fastapi import Depends, FastAPI\nfrom app.db import User, create_db_and_tables\nfrom app.schemas import UserCreate, UserRead, UserUpdate\nfrom app.users import auth_backend, current_active_user, fastapi_users\napp = FastAPI()\napp.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\n@app.get(\"/authenticated-route\")\nasync def authenticated_route(user: User = Depends(current_active_user)):\nreturn {\"message\": f\"Hello {user.email}!\"}\n@app.on_event(\"startup\")\nasync def on_startup():\n# Not needed if you setup a migration system like Alembic\nawait create_db_and_tables()\nfrom typing import AsyncGenerator\nfrom fastapi import Depends\nfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nimport uuid\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[uuid.UUID]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\n
"},{"location":"configuration/full-example/#beanie","title":"Beanie","text":"import uuid\nfrom typing import Optional\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin\nfrom fastapi_users.authentication import (\nAuthenticationBackend,\nBearerTransport,\nJWTStrategy,\n)\nfrom fastapi_users.db import SQLAlchemyUserDatabase\nfrom app.db import User, get_user_db\nSECRET = \"SECRET\"\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):\nyield UserManager(user_db)\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\nfastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])\ncurrent_active_user = fastapi_users.current_user(active=True)\nfastapi\nfastapi-users[beanie]\nuvicorn[standard]\nimport uvicorn\nif __name__ == \"__main__\":\nuvicorn.run(\"app.app:app\", host=\"0.0.0.0\", log_level=\"info\")\nfrom beanie import init_beanie\nfrom fastapi import Depends, FastAPI\nfrom app.db import User, db\nfrom app.schemas import UserCreate, UserRead, UserUpdate\nfrom app.users import auth_backend, current_active_user, fastapi_users\napp = FastAPI()\napp.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\n@app.get(\"/authenticated-route\")\nasync def authenticated_route(user: User = Depends(current_active_user)):\nreturn {\"message\": f\"Hello {user.email}!\"}\n@app.on_event(\"startup\")\nasync def on_startup():\nawait init_beanie(\ndatabase=db,\ndocument_models=[\nUser,\n],\n)\nimport motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser[PydanticObjectId]):\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nfrom beanie import PydanticObjectId\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[PydanticObjectId]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\n
"},{"location":"configuration/full-example/#what-now","title":"What now?","text":"from typing import Optional\nfrom beanie import PydanticObjectId\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, FastAPIUsers\nfrom fastapi_users.authentication import (\nAuthenticationBackend,\nBearerTransport,\nJWTStrategy,\n)\nfrom fastapi_users.db import BeanieUserDatabase, ObjectIDIDMixin\nfrom app.db import User, get_user_db\nSECRET = \"SECRET\"\nclass UserManager(ObjectIDIDMixin, BaseUserManager[User, PydanticObjectId]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db: BeanieUserDatabase = Depends(get_user_db)):\nyield UserManager(user_db)\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\nfastapi_users = FastAPIUsers[User, PydanticObjectId](get_user_manager, [auth_backend])\ncurrent_active_user = fastapi_users.current_user(active=True)\npip install 'fastapi-users[sqlalchemy,oauth]'\n
"},{"location":"configuration/oauth/#configuration","title":"Configuration","text":""},{"location":"configuration/oauth/#instantiate-an-oauth2-client","title":"Instantiate an OAuth2 client","text":"pip install 'fastapi-users[beanie,oauth]'\n
"},{"location":"configuration/oauth/#setup-the-database-adapter","title":"Setup the database adapter","text":""},{"location":"configuration/oauth/#sqlalchemy","title":"SQLAlchemy","text":"from httpx_oauth.clients.google import GoogleOAuth2\ngoogle_oauth_client = GoogleOAuth2(\"CLIENT_ID\", \"CLIENT_SECRET\")\nfrom typing import AsyncGenerator, List\nfrom fastapi import Depends\nfrom fastapi_users.db import (\nSQLAlchemyBaseOAuthAccountTableUUID,\nSQLAlchemyBaseUserTableUUID,\nSQLAlchemyUserDatabase,\n)\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, relationship, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):\npass\nclass User(SQLAlchemyBaseUserTableUUID, Base):\noauth_accounts: List[OAuthAccount] = relationship(\"OAuthAccount\", lazy=\"joined\")\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User, OAuthAccount)\nrelationship on the UserTable so that SQLAlchemy can properly retrieve the OAuth accounts of the user.SQLAlchemyBaseOAuthAccountTable as base class and define your own id and user_id column.class OAuthAccount(SQLAlchemyBaseOAuthAccountTable[int], Base):\nid = Column(Integer, primary_key=True)\n@declared_attr\ndef user_id(cls):\nreturn Column(Integer, ForeignKey(\"user.id\", ondelete=\"cascade\"), nullable=False)\nSQLAlchemyBaseOAuthAccountTable expects a generic type to define the actual type of ID you use.from typing import List\nimport motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BaseOAuthAccount, BeanieBaseUser, BeanieUserDatabase\nfrom pydantic import Field\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass OAuthAccount(BaseOAuthAccount):\npass\nclass User(BeanieBaseUser[PydanticObjectId]):\noauth_accounts: List[OAuthAccount] = Field(default_factory=list)\nasync def get_user_db():\nyield BeanieUserDatabase(User, OAuthAccount)\nOAuthAccount is not a Beanie document but a Pydantic model that we'll embed inside the User document, through the oauth_accounts array.FastAPIUsers instance, you can make it generate a single OAuth router for a given client and authentication backend.app.include_router(\nfastapi_users.get_oauth_router(google_oauth_client, auth_backend, \"SECRET\"),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\nassociate_by_email flag:app.include_router(\nfastapi_users.get_oauth_router(\ngoogle_oauth_client,\nauth_backend,\n\"SECRET\",\nassociate_by_email=True,\n),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\n
"},{"location":"configuration/oauth/#association-router-for-authenticated-users","title":"Association router for authenticated users","text":"lancelot@camelot.bt.lancelot@camelot.bt.app.include_router(\nfastapi_users.get_oauth_associate_router(google_oauth_client, UserRead, \"SECRET\"),\nprefix=\"/auth/associate/google\",\ntags=[\"auth\"],\n)\nUserRead Pydantic schema.fastapi\nfastapi-users[sqlalchemy]\nuvicorn[standard]\naiosqlite\nimport uvicorn\nif __name__ == \"__main__\":\nuvicorn.run(\"app.app:app\", host=\"0.0.0.0\", log_level=\"info\")\nfrom fastapi import Depends, FastAPI\nfrom app.db import User, create_db_and_tables\nfrom app.schemas import UserCreate, UserRead, UserUpdate\nfrom app.users import (\nSECRET,\nauth_backend,\ncurrent_active_user,\nfastapi_users,\ngoogle_oauth_client,\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\napp.include_router(\nfastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\n@app.get(\"/authenticated-route\")\nasync def authenticated_route(user: User = Depends(current_active_user)):\nreturn {\"message\": f\"Hello {user.email}!\"}\n@app.on_event(\"startup\")\nasync def on_startup():\n# Not needed if you setup a migration system like Alembic\nawait create_db_and_tables()\nfrom typing import AsyncGenerator, List\nfrom fastapi import Depends\nfrom fastapi_users.db import (\nSQLAlchemyBaseOAuthAccountTableUUID,\nSQLAlchemyBaseUserTableUUID,\nSQLAlchemyUserDatabase,\n)\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, relationship, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):\npass\nclass User(SQLAlchemyBaseUserTableUUID, Base):\noauth_accounts: List[OAuthAccount] = relationship(\"OAuthAccount\", lazy=\"joined\")\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User, OAuthAccount)\nimport uuid\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[uuid.UUID]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\n
"},{"location":"configuration/oauth/#beanie_1","title":"Beanie","text":"import os\nimport uuid\nfrom typing import Optional\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin\nfrom fastapi_users.authentication import (\nAuthenticationBackend,\nBearerTransport,\nJWTStrategy,\n)\nfrom fastapi_users.db import SQLAlchemyUserDatabase\nfrom httpx_oauth.clients.google import GoogleOAuth2\nfrom app.db import User, get_user_db\nSECRET = \"SECRET\"\ngoogle_oauth_client = GoogleOAuth2(\nos.getenv(\"GOOGLE_OAUTH_CLIENT_ID\", \"\"),\nos.getenv(\"GOOGLE_OAUTH_CLIENT_SECRET\", \"\"),\n)\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):\nyield UserManager(user_db)\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\nfastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])\ncurrent_active_user = fastapi_users.current_user(active=True)\nfastapi\nfastapi-users[beanie]\nuvicorn[standard]\nimport uvicorn\nif __name__ == \"__main__\":\nuvicorn.run(\"app.app:app\", host=\"0.0.0.0\", log_level=\"info\")\nfrom beanie import init_beanie\nfrom fastapi import Depends, FastAPI\nfrom app.db import User, db\nfrom app.schemas import UserCreate, UserRead, UserUpdate\nfrom app.users import (\nSECRET,\nauth_backend,\ncurrent_active_user,\nfastapi_users,\ngoogle_oauth_client,\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\napp.include_router(\nfastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\n@app.get(\"/authenticated-route\")\nasync def authenticated_route(user: User = Depends(current_active_user)):\nreturn {\"message\": f\"Hello {user.email}!\"}\n@app.on_event(\"startup\")\nasync def on_startup():\nawait init_beanie(\ndatabase=db,\ndocument_models=[\nUser,\n],\n)\nfrom typing import List\nimport motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BaseOAuthAccount, BeanieBaseUser, BeanieUserDatabase\nfrom pydantic import Field\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass OAuthAccount(BaseOAuthAccount):\npass\nclass User(BeanieBaseUser[PydanticObjectId]):\noauth_accounts: List[OAuthAccount] = Field(default_factory=list)\nasync def get_user_db():\nyield BeanieUserDatabase(User, OAuthAccount)\nfrom beanie import PydanticObjectId\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[PydanticObjectId]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\n
"},{"location":"configuration/overview/","title":"Overview","text":"import os\nfrom typing import Optional\nfrom beanie import PydanticObjectId\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, FastAPIUsers\nfrom fastapi_users.authentication import (\nAuthenticationBackend,\nBearerTransport,\nJWTStrategy,\n)\nfrom fastapi_users.db import BeanieUserDatabase, ObjectIDIDMixin\nfrom httpx_oauth.clients.google import GoogleOAuth2\nfrom app.db import User, get_user_db\nSECRET = \"SECRET\"\ngoogle_oauth_client = GoogleOAuth2(\nos.getenv(\"GOOGLE_OAUTH_CLIENT_ID\", \"\"),\nos.getenv(\"GOOGLE_OAUTH_CLIENT_SECRET\", \"\"),\n)\nclass UserManager(ObjectIDIDMixin, BaseUserManager[User, PydanticObjectId]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db: BeanieUserDatabase = Depends(get_user_db)):\nyield UserManager(user_db)\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\nfastapi_users = FastAPIUsers[User, PydanticObjectId](get_user_manager, [auth_backend])\ncurrent_active_user = fastapi_users.current_user(active=True)\n
"},{"location":"configuration/overview/#user-model-and-database-adapters","title":"User model and database adapters","text":"flowchart TB\n FASTAPI_USERS{FastAPIUsers}\n USER_MANAGER{UserManager}\n USER_MODEL{User model}\n DATABASE_DEPENDENCY[[get_user_db]]\n USER_MANAGER_DEPENDENCY[[get_user_manager]]\n CURRENT_USER[[current_user]]\n subgraph SCHEMAS[Schemas]\n USER[User]\n USER_CREATE[UserCreate]\n USER_UPDATE[UserUpdate]\n end\n subgraph DATABASE[Database adapters]\n SQLALCHEMY[SQLAlchemy]\n BEANIE[Beanie]\n end\n subgraph ROUTERS[Routers]\n AUTH[[get_auth_router]]\n OAUTH[[get_oauth_router]]\n OAUTH_ASSOCIATE[[get_oauth_associate_router]]\n REGISTER[[get_register_router]]\n VERIFY[[get_verify_router]]\n RESET[[get_reset_password_router]]\n USERS[[get_users_router]]\n end\n subgraph AUTH_BACKENDS[Authentication]\n subgraph TRANSPORTS[Transports]\n COOKIE[CookieTransport]\n BEARER[BearerTransport]\n end\n subgraph STRATEGIES[Strategies]\n DB[DatabaseStrategy]\n JWT[JWTStrategy]\n REDIS[RedisStrategy]\n end\n AUTH_BACKEND{AuthenticationBackend}\n end\n DATABASE --> DATABASE_DEPENDENCY\n USER_MODEL --> DATABASE_DEPENDENCY\n DATABASE_DEPENDENCY --> USER_MANAGER\n\n USER_MANAGER --> USER_MANAGER_DEPENDENCY\n USER_MANAGER_DEPENDENCY --> FASTAPI_USERS\n\n FASTAPI_USERS --> ROUTERS\n\n TRANSPORTS --> AUTH_BACKEND\n STRATEGIES --> AUTH_BACKEND\n\n AUTH_BACKEND --> ROUTERS\n AUTH_BACKEND --> FASTAPI_USERS\n\n FASTAPI_USERS --> CURRENT_USER\n\n SCHEMAS --> ROUTERSUserManager","text":"UserManager object bears most of the logic of FastAPI Users: registration, verification, password reset... We provide a BaseUserManager with this common logic; which you should overload to define how to validate passwords or handle events.UserManager object should be provided through a FastAPI dependency, get_user_manager.UserManagerFastAPIUsers and routers","text":"FastAPIUsers object is the main class from which you'll be able to generate routers for classic routes like registration or login, but also get the current_user dependency factory to inject the authenticated user in your own routes.FastAPIUsers and routersCryptContext","text":"CryptContext object of Passlib.PasswordHelper class and pass it your CryptContext. The example below shows you how you can create a CryptContext to add support for the Argon2 algorithm while deprecating BCrypt.from fastapi_users.password import PasswordHelper\nfrom passlib.context import CryptContext\ncontext = CryptContext(schemes=[\"argon2\", \"bcrypt\"], deprecated=\"auto\")\npassword_helper = PasswordHelper(context)\npassword_helper variable while instantiating your UserManager:async def get_user_manager(user_db=Depends(get_user_db)):\nyield UserManager(user_db, password_helper)\nPasswordHelper class as long as it implements the PasswordHelperProtocol and its methods.
"},{"location":"configuration/schemas/","title":"Schemas","text":"from typing import Tuple\nfrom fastapi_users.password import PasswordHelperProtocol\nclass PasswordHelper(PasswordHelperProtocol):\ndef verify_and_update(\nself, plain_password: str, hashed_password: str\n) -> Tuple[bool, str]:\n...\ndef hash(self, password: str) -> str:\n...\ndef generate(self) -> str:\n...\nUser model, which is an object that actually interacts with the database. Those schemas on the other hand are here to validate data and serialize correct it in the API.
"},{"location":"configuration/schemas/#define-your-schemas","title":"Define your schemas","text":"id (ID) \u2013 Unique identifier of the user. It matches the type of your ID, like UUID or integer.email (str) \u2013 Email of the user. Validated by email-validator.is_active (bool) \u2013 Whether or not the user is active. If not, login and forgot password requests will be denied. Defaults to True.is_verified (bool) \u2013 Whether or not the user is verified. Optional but helpful with the verify router logic. Defaults to False.is_superuser (bool) \u2013 Whether or not the user is a superuser. Useful to implement administration logic. Defaults to False.
BaseUser, which provides the basic fields and validation;BaseCreateUser, dedicated to user registration, which consists of compulsory email and password fields;BaseUpdateUser, dedicated to user profile update, which adds an optional password field;import uuid\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[uuid.UUID]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\nBaseUser class. It should correspond to the type of ID you use on your model. Here, we chose UUID, but it can be anything, like an integer or a MongoDB ObjectID.first_name, and an optional date property, birthdate.import datetime\nimport uuid\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[uuid.UUID]):\nfirst_name: str\nbirthdate: Optional[datetime.date]\nclass UserCreate(schemas.BaseUserCreate):\nfirst_name: str\nbirthdate: Optional[datetime.date]\nclass UserUpdate(schemas.BaseUserUpdate):\nfirst_name: Optional[str]\nbirthdate: Optional[datetime.date]\nUser model you defined earlier for your specific database will be the central object that will actually store the data. Therefore, you need to define the very same fields in it so the data can be actually stored.UserManager class is the core logic of FastAPI Users. We provide the BaseUserManager class which you should extend to set some parameters and define logic, for example when a user just registered or forgot its password.UserManager class","text":"UserManager class to set various parameters.import uuid\nfrom typing import Optional\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, UUIDIDMixin\nfrom .db import User, get_user_db\nSECRET = \"SECRET\"\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db=Depends(get_user_db)):\nyield UserManager(user_db)\n
User, which is the user model we defined in the database partUUIDIDMixin in the example above. It implements the parse_id method, ensuring UUID are valid and correctly parsed.
UUIDIDMixin, for UUID ID.IntegerIDMixin, for integer ID.ObjectIDIDMixin (provided by fastapi_users_db_beanie), for MongoDB ObjectID.UserManager inheritance. Because of the Method-Resolution-Order (MRO) of Python, the left-most element takes precedence.parse_id method on your UserManager class:from fastapi_users import BaseUserManager, InvalidID\nclass UserManager(BaseUserManager[User, MyCustomID]):\ndef parse_id(self, value: Any) -> MyCustomID:\ntry:\nreturn MyCustomID(value)\nexcept ValueError as e:\nraise InvalidID() from e # (1)!\n
"},{"location":"configuration/user-manager/#create-get_user_manager-dependency","title":"Create InvalidID exception.get_user_manager dependency","text":"UserManager class will be injected at runtime using a FastAPI dependency. This way, you can run it in a database session or swap it with a mock during testing.import uuid\nfrom typing import Optional\nfrom fastapi import Depends, Request\nfrom fastapi_users import BaseUserManager, UUIDIDMixin\nfrom .db import User, get_user_db\nSECRET = \"SECRET\"\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nasync def get_user_manager(user_db=Depends(get_user_db)):\nyield UserManager(user_db)\nget_user_db dependency we defined earlier to inject the database instance.
"},{"location":"configuration/user-manager/#methods","title":"Methods","text":""},{"location":"configuration/user-manager/#validate_password","title":"reset_password_token_secret: Secret to encode reset password token. Use a strong passphrase and keep it secure.reset_password_token_lifetime_seconds: Lifetime of reset password token. Defaults to 3600.reset_password_token_audience: JWT audience of reset password token. Defaults to fastapi-users:reset.verification_token_secret: Secret to encode verification token. Use a strong passphrase and keep it secure.verification_token_lifetime_seconds: Lifetime of verification token. Defaults to 3600.verification_token_audience: JWT audience of verification token. Defaults to fastapi-users:verify.validate_password","text":"
password (str): the password to validate.user (Union[UserCreate, User]): user model which we are currently validating the password. Useful if you want to check that the password doesn't contain the name or the birthdate of the user for example.None if the password is valid or raise InvalidPasswordException if not. This exception expects an argument reason telling why the password is invalid. It'll be part of the error response.
"},{"location":"configuration/user-manager/#on_after_register","title":"from fastapi_users import BaseUserManager, InvalidPasswordException, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def validate_password(\nself,\npassword: str,\nuser: Union[UserCreate, User],\n) -> None:\nif len(password) < 8:\nraise InvalidPasswordException(\nreason=\"Password should be at least 8 characters\"\n)\nif user.email in password:\nraise InvalidPasswordException(\nreason=\"Password should not contain e-mail\"\n)\non_after_register","text":"
user (User): the registered user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_update","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\non_after_update","text":"
user (User): the updated user.update_dict (Dict[str, Any]): dictionary with the updated user fields.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_login","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_update(\nself,\nuser: User,\nupdate_dict: Dict[str, Any],\nrequest: Optional[Request] = None,\n):\nprint(f\"User {user.id} has been updated with {update_dict}.\")\non_after_login","text":"
user (User): the updated user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_request_verify","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_login(\nself,\nuser: User,\nrequest: Optional[Request] = None,\n):\nprint(f\"User {user.id} logged in.\")\non_after_request_verify","text":"
user (User): the user to verify.token (str): the verification token.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_verify","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\non_after_verify","text":"
user (User): the verified user.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_forgot_password","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_verify(\nself, user: User, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has been verified\")\non_after_forgot_password","text":"
user (User): the user that forgot its password.token (str): the forgot password tokenrequest (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_reset_password","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\non_after_reset_password","text":"
user (User): the user that reset its password.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_before_delete","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_reset_password(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has reset their password.\")\non_before_delete","text":"
user (User): the user to be deleted.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/user-manager/#on_after_delete","title":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_before_delete(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} is going to be deleted\")\non_after_delete","text":"
user (User): the user to be deleted.request (Optional[Request]): optional FastAPI request object that triggered the operation. Defaults to None.
"},{"location":"configuration/authentication/","title":"Authentication","text":"from fastapi_users import BaseUserManager, UUIDIDMixin\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n# ...\nasync def on_after_delete(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} is successfully deleted\")\nHTTPException is raised./login and /logout. More on this in the routers documentation.Authorization: Bearer header.
AuthenticationBackend class.from fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy\nSECRET = \"SECRET\"\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\n
"},{"location":"configuration/authentication/backend/#next-steps","title":"Next steps","text":"name (str): Name of the backend. Each backend should have a unique name.transport (Transport): An instance of a Transport class.get_strategy (Callable[..., Strategy]): A dependency callable returning an instance of a Strategy class.FastAPIUsers instance and generate an auth router for each one of them.
token (str) \u2013 Unique identifier of the token. It's generated automatically upon login by the strategy.user_id (ID) \u2013 User id. of the user associated to this token.created_at (datetime) \u2013 Date and time of creation of the token. It's used to determine if the token is expired or not.from typing import AsyncGenerator\nfrom fastapi import Depends\nfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\nfrom fastapi_users_db_sqlalchemy.access_token import (\nSQLAlchemyAccessTokenDatabase,\nSQLAlchemyBaseAccessTokenTableUUID,\n)\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nclass AccessToken(SQLAlchemyBaseAccessTokenTableUUID, Base): # (1)!\npass\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nasync def get_access_token_db(\nsession: AsyncSession = Depends(get_async_session),\n): # (2)!\nyield SQLAlchemyAccessTokenDatabase(session, AccessToken)\n
AccessToken ORM model inheriting from SQLAlchemyBaseAccessTokenTableUUID.SQLAlchemyAccessTokenDatabase class. Just like the user database adapter, it expects a fresh SQLAlchemy session and the AccessToken model class we defined above.user_id foreign key is defined as UUIDSQLAlchemyBaseAccessTokenTable as base class and define your own user_id column.class AccessToken(SQLAlchemyBaseAccessTokenTable[int], Base):\n@declared_attr\ndef user_id(cls):\nreturn Column(Integer, ForeignKey(\"user.id\", ondelete=\"cascade\"), nullable=False)\nSQLAlchemyBaseAccessTokenTable expects a generic type to define the actual type of ID you use.import motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nfrom fastapi_users_db_beanie.access_token import (\nBeanieAccessTokenDatabase,\nBeanieBaseAccessToken,\n)\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser):\npass\nclass AccessToken(BeanieBaseAccessToken[PydanticObjectId]): # (1)!\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nasync def get_access_token_db(): # (2)!\nyield BeanieAccessTokenDatabase(AccessToken)\n
"},{"location":"configuration/authentication/strategies/database/#strategy","title":"Strategy","text":"AccessToken ODM model inheriting from BeanieBaseAccessToken. Notice that we set a generic type to define the type of the user_id reference. By default, it's a standard MongoDB ObjectID.BeanieAccessTokenDatabase class. Just like the user database adapter, it expects the AccessToken model class we defined above.import uuid\nfrom fastapi import Depends\nfrom fastapi_users.authentication.strategy.db import AccessTokenDatabase, DatabaseStrategy\nfrom .db import AccessToken, User\ndef get_database_strategy(\naccess_token_db: AccessTokenDatabase[AccessToken] = Depends(get_access_token_db),\n) -> DatabaseStrategy:\nreturn DatabaseStrategy(access_token_db, lifetime_seconds=3600)\n
database (AccessTokenDatabase): A database adapter instance for AccessToken table, like we defined above.lifetime_seconds (int): The lifetime of the token in seconds.from fastapi_users.authentication import JWTStrategy\nSECRET = \"SECRET\"\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\n
secret (Union[str, pydantic.SecretStr]): A constant secret which is used to encode the token. Use a strong passphrase and keep it secure.lifetime_seconds (Optional[int]): The lifetime of the token in seconds. Can be set to None but in this case the token will be valid forever; which may raise serious security concerns.token_audience (Optional[List[str]]): A list of valid audiences for the JWT token. Defaults to [\"fastapi-users:auth\"].algorithm (Optional[str]): The JWT encryption algorithm. See RFC 7519, section 8. Defaults to \"HS256\".public_key (Optional[Union[str, pydantic.SecretStr]]): If the JWT encryption algorithm requires a key pair instead of a simple secret, the key to decrypt the JWT may be provided here. The secret parameter will always be used to encrypt the JWT.JWTStrategy, since it doesn't require dependencies, it can be as simple as the function above.
"},{"location":"configuration/authentication/strategies/jwt/#logout","title":"Logout","text":"from fastapi_users.authentication import JWTStrategy\nPUBLIC_KEY = \"\"\"-----BEGIN PUBLIC KEY-----\n# Your RSA public key in PEM format goes here\n-----END PUBLIC KEY-----\"\"\"\nPRIVATE_KEY = \"\"\"-----BEGIN RSA PRIVATE KEY-----\n# Your RSA private key in PEM format goes here\n-----END RSA PRIVATE KEY-----\"\"\"\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(\nsecret=PRIVATE_KEY, \nlifetime_seconds=3600,\nalgorithm=\"RS256\",\npublic_key=PUBLIC_KEY,\n)\n
"},{"location":"configuration/authentication/strategies/redis/#configuration","title":"Configuration","text":"pip install 'fastapi-users[redis]'\nimport redis.asyncio\nfrom fastapi_users.authentication import RedisStrategy\nredis = redis.asyncio.from_url(\"redis://localhost:6379\", decode_responses=True)\ndef get_redis_strategy() -> RedisStrategy:\nreturn RedisStrategy(redis, lifetime_seconds=3600)\n
redis (redis.asyncio.Redis): An instance of redis.asyncio.Redis. Note that the decode_responses flag set to True is necessary.lifetime_seconds (Optional[int]): The lifetime of the token in seconds. Defaults to None, which means the token doesn't expire.key_prefix (str): The prefix used to set the key in the Redis stored. Defaults to fastapi_users_token:.Authorization header of the HTTP request with the Bearer scheme. It's particularly suited for pure API interaction or mobile apps.from fastapi_users.authentication import BearerTransport\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\n
"},{"location":"configuration/authentication/transports/bearer/#login","title":"Login","text":"tokenUrl (str): The exact path of your login endpoint. It'll allow the interactive documentation to automatically discover it and get a working Authorize button. In most cases, you'll probably need a relative path, not absolute. You can read more details about this in the FastAPI documentation.200 OK{\n\"access_token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI\",\n\"token_type\": \"bearer\"\n}\nBearer authentication with a valid token corresponding to your strategy.
"},{"location":"configuration/authentication/transports/cookie/","title":"Cookie","text":"curl http://localhost:9000/protected-route -H'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI'\nfrom fastapi_users.authentication import CookieTransport\ncookie_transport = CookieTransport(cookie_max_age=3600)\n
"},{"location":"configuration/authentication/transports/cookie/#login","title":"Login","text":"cookie_name (fastapiusersauth): Name of the cookie.cookie_max_age (Optional[int]): The lifetime of the cookie in seconds. None by default, which means it's a session cookie.cookie_path (/): Cookie path.cookie_domain (None): Cookie domain.cookie_secure (True): Whether to only send the cookie to the server via SSL request.cookie_httponly (True): Whether to prevent access to the cookie via JavaScript.cookie_samesite (lax): A string that specifies the samesite strategy for the cookie. Valid values are lax, strict and none. Defaults to lax.set-cookie header upon successful login:200 OK200 OKimport motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser[PydanticObjectId]):\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nUser model.import motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser[PydanticObjectId]):\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nUser table. You can of course add you own fields there to fit to your needs!id field:import uuid\nfrom pydantic import Field\nclass User(BeanieBaseUser[uuid.UUID]):\nid: uuid.UUID = Field(default_factory=uuid.uuid4)\nBeanieBaseUser expects a generic type to define the actual type of ID you use.id and email.import motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser[PydanticObjectId]):\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nUser model we defined above.from beanie import init_beanie\n@app.on_event(\"startup\")\nasync def on_startup():\nawait init_beanie(\ndatabase=db, # (1)!\ndocument_models=[\nUser, # (2)!\n],\n)\n
"},{"location":"configuration/databases/sqlalchemy/","title":"SQLAlchemy","text":"db Motor database instance we defined above.User model we defined above. Don't forget to also add your very own models!
pip install asyncpgpip install aiosqliteDB_URLs are:
engine = create_engine('postgresql+asyncpg://user:password@host:port/name')engine = create_engine('sqlite+aiosqlite:///name.db')User model.from typing import AsyncGenerator\nfrom fastapi import Depends\nfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nUser table. You can of course add you own fields there to fit to your needs!SQLAlchemyBaseUserTable as base class and define your own id column.class User(SQLAlchemyBaseUserTable[int], Base):\nid = Column(Integer, primary_key=True)\nSQLAlchemyBaseUserTable expects a generic type to define the actual type of ID you use.from typing import AsyncGenerator\nfrom fastapi import Depends\nfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nfrom typing import AsyncGenerator\nfrom fastapi import Depends\nfrom fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import DeclarativeMeta, declarative_base, sessionmaker\nDATABASE_URL = \"sqlite+aiosqlite:///./test.db\"\nBase: DeclarativeMeta = declarative_base()\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nengine = create_async_engine(DATABASE_URL)\nasync_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\nasync def create_db_and_tables():\nasync with engine.begin() as conn:\nawait conn.run_sync(Base.metadata.create_all)\nasync def get_async_session() -> AsyncGenerator[AsyncSession, None]:\nasync with async_session_maker() as session:\nyield session\nasync def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nget_async_session dependency returning us a fresh SQLAlchemy session to interact with the database.get_user_db dependency to generate our adapter. Notice that we pass it two things:
"},{"location":"configuration/routers/","title":"Routers","text":"session instance we just injected.User class, which is the actual SQLAlchemy model.FastAPIUsers object that will wire the user manager, the authentication classes and let us generate the actual API routes.FastAPIUsers","text":"FastAPIUsers object with the elements we defined before. More precisely:
get_user_manager: Dependency callable getter to inject the user manager class instance. See UserManager.auth_backends: List of authentication backends. See Authentication.import uuid\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\n
User, which is the user model we defined in the database part
/login and /logout routes for a given authentication backend./register routes to allow a user to create a new account./forgot-password and /reset-password routes to allow a user to reset its password./request-verify-token and /verify routes to manage user e-mail verification./login and /logout routes for a given authentication backend.
"},{"location":"configuration/routers/auth/#optional-user-verification","title":"Optional: user verification","text":"import uuid\nfrom fastapi import FastAPI\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_auth_router(auth_backend),\nprefix=\"/auth/jwt\",\ntags=[\"auth\"],\n)\nis_verified property set to True) to allow login. You have to set the requires_verification parameter to True on the router instantiation method:
"},{"location":"configuration/routers/register/","title":"Register routes","text":"app.include_router(\nfastapi_users.get_auth_router(auth_backend, requires_verification=True),\nprefix=\"/auth/jwt\",\ntags=[\"auth\"],\n)\n/register route to allow a user to create a new account.
"},{"location":"configuration/routers/reset/","title":"Reset password router","text":"import uuid\nfrom fastapi import FastAPI\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfrom .schemas import UserCreate, UserRead\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\n/forgot-password (the user asks for a token to reset its password) and /reset-password (the user changes its password given the token) routes.
"},{"location":"configuration/routers/users/","title":"Users router","text":"import uuid\nfrom fastapi import FastAPI\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\n
"},{"location":"configuration/routers/users/#optional-user-verification","title":"Optional: user verification","text":"import uuid\nfrom fastapi import FastAPI\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfrom .schemas import UserRead, UserUpdate\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\nis_verified property set to True) to access those routes. You have to set the requires_verification parameter to True on the router instantiation method:
"},{"location":"configuration/routers/verify/","title":"Verify router","text":"app.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate, requires_verification=True),\nprefix=\"/users\",\ntags=[\"users\"],\n)\n
"},{"location":"cookbook/create-user-programmatically/","title":"Create a user programmatically","text":"import uuid\nfrom fastapi import FastAPI\nfrom fastapi_users import FastAPIUsers\nfrom .db import User\nfrom .schemas import UserRead\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\napp = FastAPI()\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\nUserManager class and all other dependent objects manually.yield keyword. FastAPI knows very well to handle them inside its dependency injection system. For example, here is the definition of the get_user_manager dependency:async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):\nyield UserManager(user_db)\nfor loop, which would be a bit unnatural in this context since we have only one value to get, the user manager instance. To avoid this, we'll transform them into context managers, so we can call them using the with..as syntax. Fortunately, the standard library provides tools to automatically transform generators into context managers.contextlib.asynccontextmanager:import contextlib\nfrom app.db import get_async_session, get_user_db\nfrom app.schemas import UserCreate\nfrom app.users import get_user_manager\nfrom fastapi_users.exceptions import UserAlreadyExists\nget_async_session_context = contextlib.asynccontextmanager(get_async_session)\nget_user_db_context = contextlib.asynccontextmanager(get_user_db)\nget_user_manager_context = contextlib.asynccontextmanager(get_user_manager)\nasync def create_user(email: str, password: str, is_superuser: bool = False):\ntry:\nasync with get_async_session_context() as session:\nasync with get_user_db_context(session) as user_db:\nasync with get_user_manager_context(user_db) as user_manager:\nuser = await user_manager.create(\nUserCreate(\nemail=email, password=password, is_superuser=is_superuser\n)\n)\nprint(f\"User created {user}\")\nexcept UserAlreadyExists:\nprint(f\"User {email} already exists\")\n
"},{"location":"cookbook/create-user-programmatically/#3-use-it","title":"3. Use it","text":"import contextlib\nfrom app.db import get_async_session, get_user_db\nfrom app.schemas import UserCreate\nfrom app.users import get_user_manager\nfrom fastapi_users.exceptions import UserAlreadyExists\nget_async_session_context = contextlib.asynccontextmanager(get_async_session)\nget_user_db_context = contextlib.asynccontextmanager(get_user_db)\nget_user_manager_context = contextlib.asynccontextmanager(get_user_manager)\nasync def create_user(email: str, password: str, is_superuser: bool = False):\ntry:\nasync with get_async_session_context() as session:\nasync with get_user_db_context(session) as user_db:\nasync with get_user_manager_context(user_db) as user_manager:\nuser = await user_manager.create(\nUserCreate(\nemail=email, password=password, is_superuser=is_superuser\n)\n)\nprint(f\"User created {user}\")\nexcept UserAlreadyExists:\nprint(f\"User {email} already exists\")\n
"},{"location":"migration/08_to_1x/","title":"0.8.x \u27a1\ufe0f 1.x.x","text":"import asyncio\nif __name__ == \"__main__\":\nasyncio.run(create_user(\"king.arthur@camelot.bt\", \"guinevere\"))\n# Before\nassert \"d35d213e-f3d8-4f08-954a-7e0d1bea286f\" == user.id\n# Now\nassert \"d35d213e-f3d8-4f08-954a-7e0d1bea286f\" == str(user.id)\nUUID4 type instead of str:
"},{"location":"migration/08_to_1x/#mongodb","title":"MongoDB","text":"from pydantic import BaseModel, UUID4\n# Before\nclass Model(BaseModel):\nuser_id: str\n# After\nclass Model(BaseModel):\nuser_id: UUID4\nstandard UUID representation when instantiating the MongoDB client:DATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\npythonLegacy but new applications should consider setting this to standard for cross language compatibility. Read more about this.uuid-ossp extension:CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";\n
"},{"location":"migration/08_to_1x/#mysql","title":"MySQL","text":"ALTER TABLE \"user\" ADD uuid_id UUID;\nUPDATE \"user\" SET uuid_id = uuid(id);\nALTER TABLE \"user\" DROP id;\nALTER TABLE \"user\" ADD PRIMARY KEY (uuid_id);\nALTER TABLE \"user\" RENAME COLUMN uuid_id TO id;\nCHAR(36) type:
"},{"location":"migration/08_to_1x/#mongodb_1","title":"MongoDB","text":""},{"location":"migration/08_to_1x/#mongo-shell","title":"Mongo shell","text":"ALTER TABLE \"user\" MODIFY id CHAR(36);\nforEach iterator to convert the id. for each document:
"},{"location":"migration/08_to_1x/#python","title":"Python","text":"db.getCollection('users').find().forEach(function(user) {\nvar uuid = UUID(user.id);\ndb.getCollection('users').update({_id: user._id}, [{$set: {id: uuid}}]);\n});\n
"},{"location":"migration/08_to_1x/#splitted-routers","title":"Splitted routers","text":"import uuid\nimport motor.motor_asyncio\nasync def migrate_uuid():\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nusers = db[\"users\"]\nasync for user in users.find({}):\nawait users.update_one(\n{\"_id\": user[\"_id\"]},\n{\"$set\": {\"id\": uuid.UUID(user[\"id\"])}},\n)\n
"},{"location":"migration/08_to_1x/#after","title":"After","text":"jwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)\napp = FastAPI()\nfastapi_users = FastAPIUsers(\nuser_db, [jwt_authentication], User, UserCreate, UserUpdate, UserDB,\n)\napp.include_router(fastapi_users.router, prefix=\"/users\", tags=[\"users\"])\n@fastapi_users.on_after_register()\ndef on_after_register(user: User, request: Request):\nprint(f\"User {user.id} has registered.\")\n@fastapi_users.on_after_forgot_password()\ndef on_after_forgot_password(user: User, token: str, request: Request):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\ndef on_after_register(user: UserDB, request: Request):\nprint(f\"User {user.id} has registered.\")\ndef on_after_forgot_password(user: UserDB, token: str, request: Request):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\njwt_authentication = JWTAuthentication(secret=SECRET, lifetime_seconds=3600)\napp = FastAPI()\nfastapi_users = FastAPIUsers(\nuser_db, [jwt_authentication], User, UserCreate, UserUpdate, UserDB,\n)\napp.include_router(\nfastapi_users.get_auth_router(jwt_authentication), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(on_after_register), prefix=\"/auth\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_reset_password_router(\nSECRET, after_forgot_password=on_after_forgot_password\n),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(fastapi_users.get_users_router(), prefix=\"/users\", tags=[\"users\"])\n
"},{"location":"migration/1x_to_2x/","title":"1.x.x \u27a1\ufe0f 2.x.x","text":""},{"location":"migration/1x_to_2x/#jwt-authentication-backend","title":"JWT authentication backend","text":"FastAPIUsers takes two arguments less (reset_password_token_secret and reset_password_token_lifetime_seconds)./login//logout are now your responsibility to include for each backend. The path will change (before /login/jwt, after /jwt/login).{\n\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI\"\n}\n{\n\"access_token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI\",\n\"token_type\": \"bearer\"\n}\nking.arthur@camelot.bt and King.Arthur@camelot.bt were considered as two different users. This behaviour was a bit confusing and not consistent with 99% of web services out there.King.Arthur@camelot.bt, it will be stored exactly like this in the database (with casing) ; but he will be able to login as king.arthur@camelot.bt.expires_at property in OAuthAccount is now optional","text":"expires_at property in OAuthAccount model was mandatory. It was causing issues with some services that don't have such expiration property.is_verified in User model.","text":"is_verified property has been added to the User model.
current_user factory instead. [Documentation]UserUpdate model shouldn't inherit from the base User class. If you have custom fields, you should repeat them in this model. [Documentation]
"},{"location":"migration/7x_to_8x/","title":"7.x.x \u27a1\ufe0f 8.x.x","text":"import statements remain unchanged.UserManager class and a associated dependency to create an instance of this class.UserManager","text":"on_after_register or on_after_forgot_password were defined in their own functions that were passed as arguments of router generators.UserManager class.UserManager documentation.UserManager","text":"FastAPIUsers.UserManager class.UserManager documentation.UserManager","text":"get_verify_router.UserManager class.UserManager documentation.UserManager","text":"get_verify_router.UserManager class.UserManager documentation.get_user_manager dependency","text":"FastAPIUsers.get_user_manager dependency returning an instance of your UserManager class. This dependency will be dependent of the database adapter dependency.UserManager documentation and FastAPIUsers documentationfrom fastapi_users.authentication import JWTAuthentication\njwt_authentication = JWTAuthentication(\nsecret=SECRET, lifetime_seconds=3600, tokenUrl=\"auth/jwt/login\"\n)\nfrom fastapi_users.authentication import AuthenticationBackend, BearerTransport, JWTStrategy\nSECRET = \"SECRET\"\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\nname anymore: you need to provide it yourself for each of your backends.from fastapi_users.authentication import CookieAuthentication\ncookie_authentication = CookieAuthentication(secret=SECRET, lifetime_seconds=3600)\nfrom fastapi_users.authentication import AuthenticationBackend, CookieTransport, JWTStrategy\nSECRET = \"SECRET\"\ncookie_transport = CookieTransport(cookie_max_age=3600)\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\nauth_backend = AuthenticationBackend(\nname=\"cookie\",\ntransport=cookie_transport,\nget_strategy=get_jwt_strategy,\n)\nname anymore: you need to provide it yourself for each of your backends.app.include_router(\nfastapi_users.get_oauth_router(google_oauth_client, \"SECRET\"),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\n
"},{"location":"migration/8x_to_9x/#authentication_backend-is-not-needed-on-authorize","title":"app.include_router(\nfastapi_users.get_oauth_router(google_oauth_client, auth_backend, \"SECRET\"),\nprefix=\"/auth/google\",\ntags=[\"auth\"],\n)\nauthentication_backend is not needed on /authorize","text":"/authorize.curl \\\n-H \"Content-Type: application/json\" \\\n-X GET \\\nhttp://localhost:8000/auth/google/authorize?authentication_backend=jwt\n
"},{"location":"migration/8x_to_9x/#lost","title":"Lost?","text":"curl \\\n-H \"Content-Type: application/json\" \\\n-X GET \\\nhttp://localhost:8000/auth/google/authorize\ncurrent_user dependency would return you an instance of UserDB, a Pydantic model. This proved to be quite problematic with some ORM if you ever needed to retrieve relationship data or make specific requests.fastapi-users[sqlalchemy].fastapi\nfastapi-users[sqlalchemy2]\nuvicorn[standard]\naiosqlite\nfastapi\nfastapi-users[sqlalchemy]\nuvicorn[standard]\naiosqlite\nUserTable to User: it's not a compulsory change, but since there is no risk of confusion with Pydantic models anymore, it's probably a more idiomatic naming.class UserTable(Base, SQLAlchemyBaseUserTable):\npass\nclass User(SQLAlchemyBaseUserTableUUID, Base):\npass\nSQLAlchemyUserDatabase adapter now only expects this User model. UserDB is removed.async def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(UserDB, session, UserTable)\n
"},{"location":"migration/9x_to_10x/#mongodb","title":"MongoDB","text":"async def get_user_db(session: AsyncSession = Depends(get_async_session)):\nyield SQLAlchemyUserDatabase(session, User)\nfastapi\nfastapi-users[mongodb]\nuvicorn[standard]\naiosqlite\nfastapi\nfastapi-users[beanie]\nuvicorn[standard]\naiosqlite\nimport os\nimport motor.motor_asyncio\nfrom fastapi_users.db import MongoDBUserDatabase\nfrom app.models import UserDB\nDATABASE_URL = os.environ[\"DATABASE_URL\"]\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\ncollection = db[\"users\"]\nasync def get_user_db():\nyield MongoDBUserDatabase(UserDB, collection)\nimport motor.motor_asyncio\nfrom beanie import PydanticObjectId\nfrom fastapi_users.db import BeanieBaseUser, BeanieUserDatabase\nDATABASE_URL = \"mongodb://localhost:27017\"\nclient = motor.motor_asyncio.AsyncIOMotorClient(\nDATABASE_URL, uuidRepresentation=\"standard\"\n)\ndb = client[\"database_name\"]\nclass User(BeanieBaseUser[PydanticObjectId]):\npass\nasync def get_user_db():\nyield BeanieUserDatabase(User)\nid field:import uuid\nfrom pydantic import Field\nclass User(BeanieBaseUser[uuid.UUID]):\nid: uuid.UUID = Field(default_factory=uuid.uuid4)\n
"},{"location":"migration/9x_to_10x/#tortoise-orm-and-ormar","title":"Tortoise ORM and ormar","text":"from beanie import init_beanie\n@app.on_event(\"startup\")\nasync def on_startup():\nawait init_beanie(\ndatabase=db,\ndocument_models=[\nUser,\n],\n)\nUserManager","text":"UserManager class. In particular, it now needs a parse_id method that can be provided through built-in mixins.user_db_model class property is removed.class UserManager(BaseUserManager[UserCreate, UserDB]):\nuser_db_model = UserDB\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: UserDB, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: UserDB, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: UserDB, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nclass UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\nreset_password_token_secret = SECRET\nverification_token_secret = SECRET\nasync def on_after_register(self, user: User, request: Optional[Request] = None):\nprint(f\"User {user.id} has registered.\")\nasync def on_after_forgot_password(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"User {user.id} has forgot their password. Reset token: {token}\")\nasync def on_after_request_verify(\nself, user: User, token: str, request: Optional[Request] = None\n):\nprint(f\"Verification requested for user {user.id}. Verification token: {token}\")\nUserDB has been removed in favor of native models.User to UserRead: it's not a compulsory change, but since there is a risk of confusion with the native model, it's highly recommended.BaseUser schema now accepts a generic type to specify the type of ID you use.from fastapi_users import models\nclass User(models.BaseUser):\npass\nclass UserCreate(models.BaseUserCreate):\npass\nclass UserUpdate(models.BaseUserUpdate):\npass\nclass UserDB(User, models.BaseUserDB):\npass\n
"},{"location":"migration/9x_to_10x/#fastapi-users-and-routers","title":"FastAPI Users and routers","text":"import uuid\nfrom fastapi_users import schemas\nclass UserRead(schemas.BaseUser[uuid.UUID]):\npass\nclass UserCreate(schemas.BaseUserCreate):\npass\nclass UserUpdate(schemas.BaseUserUpdate):\npass\nFastAPIUsers class:fastapi_users = FastAPIUsers(\nget_user_manager,\n[auth_backend],\nUser,\nUserCreate,\nUserUpdate,\nUserDB,\n)\nfastapi_users = FastAPIUsers[User, uuid.UUID](\nget_user_manager,\n[auth_backend],\n)\nget_register_router, get_verify_router and get_users_router.app.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(fastapi_users.get_register_router(), prefix=\"/auth\", tags=[\"auth\"])\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(fastapi_users.get_users_router(), prefix=\"/users\", tags=[\"users\"])\n
"},{"location":"migration/9x_to_10x/#lost","title":"Lost?","text":"app.include_router(\nfastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n)\napp.include_router(\nfastapi_users.get_register_router(UserRead, UserCreate),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_reset_password_router(),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_verify_router(UserRead),\nprefix=\"/auth\",\ntags=[\"auth\"],\n)\napp.include_router(\nfastapi_users.get_users_router(UserRead, UserUpdate),\nprefix=\"/users\",\ntags=[\"users\"],\n)\nFastAPIUsers instance.current_user","text":"
optional: If True, None is returned if there is no authenticated user or if it doesn't pass the other requirements. Otherwise, throw 401 Unauthorized. Defaults to False.active: If True, throw 401 Unauthorized if the authenticated user is inactive. Defaults to False.verified: If True, throw 403 Forbidden if the authenticated user is not verified. Defaults to False.superuser: If True, throw 403 Forbidden if the authenticated user is not a superuser. Defaults to False.get_enabled_backends: Optional dependency callable returning a list of enabled authentication backends. Useful if you want to dynamically enable some authentication backends based on external logic, like a configuration in database. By default, all specified authentication backends are enabled. Please not however that every backends will appear in the OpenAPI documentation, as FastAPI resolves it statically.
"},{"location":"usage/current-user/#get-the-current-active-user","title":"Get the current active user","text":"current_user = fastapi_users.current_user()\n@app.get(\"/protected-route\")\ndef protected_route(user: User = Depends(current_user)):\nreturn f\"Hello, {user.email}\"\n
"},{"location":"usage/current-user/#get-the-current-active-and-verified-user","title":"Get the current active and verified user","text":"current_active_user = fastapi_users.current_user(active=True)\n@app.get(\"/protected-route\")\ndef protected_route(user: User = Depends(current_active_user)):\nreturn f\"Hello, {user.email}\"\n
"},{"location":"usage/current-user/#get-the-current-active-superuser","title":"Get the current active superuser","text":"current_active_verified_user = fastapi_users.current_user(active=True, verified=True)\n@app.get(\"/protected-route\")\ndef protected_route(user: User = Depends(current_active_verified_user)):\nreturn f\"Hello, {user.email}\"\n
"},{"location":"usage/current-user/#dynamically-enable-authentication-backends","title":"Dynamically enable authentication backends","text":"current_superuser = fastapi_users.current_user(active=True, superuser=True)\n@app.get(\"/protected-route\")\ndef protected_route(user: User = Depends(current_superuser)):\nreturn f\"Hello, {user.email}\"\n
"},{"location":"usage/current-user/#in-a-path-operation","title":"In a path operation","text":"from fastapi import Request\nfrom fastapi_users.authentication import AuthenticationBackend, BearerTransport, CookieTransport, JWTStrategy\nSECRET = \"SECRET\"\nbearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\ncookie_transport = CookieTransport(cookie_max_age=3600)\ndef get_jwt_strategy() -> JWTStrategy:\nreturn JWTStrategy(secret=SECRET, lifetime_seconds=3600)\njwt_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=bearer_transport,\nget_strategy=get_jwt_strategy,\n)\ncookie_backend = AuthenticationBackend(\nname=\"jwt\",\ntransport=cookie_transport,\nget_strategy=get_jwt_strategy,\n)\nasync def get_enabled_backends(request: Request):\n\"\"\"Return the enabled dependencies following custom logic.\"\"\"\nif request.url.path == \"/protected-route-only-jwt\":\nreturn [jwt_backend]\nelse:\nreturn [cookie_backend, jwt_backend]\ncurrent_active_user = fastapi_users.current_user(active=True, get_enabled_backends=get_enabled_backends)\n@app.get(\"/protected-route\")\ndef protected_route(user: User = Depends(current_active_user)):\nreturn f\"Hello, {user.email}. You are authenticated with a cookie or a JWT.\"\n@app.get(\"/protected-route-only-jwt\")\ndef protected_route(user: User = Depends(current_active_user)):\nreturn f\"Hello, {user.email}. You are authenticated with a JWT.\"\n@app.get(\"/protected-route\", dependencies=[Depends(current_superuser)])\ndef protected_route():\nreturn \"Hello, some user.\"\ncURL and an axios example.curl \\\n-H \"Content-Type: application/json\" \\\n-X POST \\\n-d \"{\\\"email\\\": \\\"king.arthur@camelot.bt\\\",\\\"password\\\": \\\"guinevere\\\"}\" \\\nhttp://localhost:8000/auth/register\n
"},{"location":"usage/flow/#response","title":"Response","text":"axios.post('http://localhost:8000/auth/register', {\nemail: 'king.arthur@camelot.bt',\npassword: 'guinevere',\n})\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\n{\n\"id\": \"4fd3477b-eccf-4ee3-8f7d-68ad72261476\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\n
"},{"location":"usage/flow/#2-login","title":"2. Login","text":"User model (like a first name or a birthdate), you'll have to provide them in the payload.is_active or is_superuser itself at registration. Only a superuser can do it by PATCHing the user.curl \\\n-H \"Content-Type: multipart/form-data\" \\\n-X POST \\\n-F \"username=king.arthur@camelot.bt\" \\\n-F \"password=guinevere\" \\\nhttp://localhost:8000/auth/jwt/login\nconst formData = new FormData();\nformData.set('username', 'king.arthur@camelot.bt');\nformData.set('password', 'guinevere');\naxios.post(\n'http://localhost:8000/auth/jwt/login',\nformData,\n{\nheaders: {\n'Content-Type': 'multipart/form-data',\n},\n},\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\nusername.{\n\"access_token\":\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM\",\n\"token_type\": \"bearer\"\n}\nking.arthur@camelot.bt. We'll see how in the next section.curl \\\n-v \\\n-H \"Content-Type: multipart/form-data\" \\\n-X POST \\\n-F \"username=king.arthur@camelot.bt\" \\\n-F \"password=guinevere\" \\\nhttp://localhost:8000/auth/cookie/login\nconst formData = new FormData();\nformData.set('username', 'king.arthur@camelot.bt');\nformData.set('password', 'guinevere');\naxios.post(\n'http://localhost:8000/auth/cookie/login',\nformData,\n{\nheaders: {\n'Content-Type': 'multipart/form-data',\n},\n},\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\nusername.Set-Cookie header (that's why we added the -v option in cURL to see them).set-cookie: fastapiusersauth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYzYwNjBmMTEtNTM0OS00YTI0LThiNGEtYTJhODc1ZGM1Mzk1IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4OTQ3fQ.qNA4oPVYhoqrJIk-zvAyEfEVoEnP156G30H_SWEU0sU; HttpOnly; Max-Age=3600; Path=/; Secure\nking.arthur@camelot.bt by setting a Cookie header with this cookie.export TOKEN=\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM\";\ncurl \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-X GET \\\nhttp://localhost:8000/users/me\n
"},{"location":"usage/flow/#response_3","title":"Response","text":"const TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM';\naxios.get(\n'http://localhost:8000/users/me', {\nheaders: {\n'Authorization': `Bearer ${TOKEN}`,\n},\n})\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\n{\n\"id\": \"4fd3477b-eccf-4ee3-8f7d-68ad72261476\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\ncurl \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-X PATCH \\\n-d \"{\\\"password\\\": \\\"lancelot\\\"}\" \\\nhttp://localhost:8000/users/me\n
"},{"location":"usage/flow/#response_4","title":"Response","text":"axios.patch(\n'http://localhost:8000/users/me',\n{\npassword: 'lancelot',\n},\n{\nheaders: {\n'Authorization': `Bearer ${TOKEN}`,\n},\n},\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\n{\n\"id\": \"4fd3477b-eccf-4ee3-8f7d-68ad72261476\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\nis_active or is_superuser itself. Only a superuser can do it by PATCHing the user.is_superuser column/property to true.curl \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-X GET \\\nhttp://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476\n
"},{"location":"usage/flow/#response_5","title":"Response","text":"axios.get(\n'http://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476', {\nheaders: {\n'Authorization': `Bearer ${TOKEN}`,\n},\n})\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\n
"},{"location":"usage/flow/#51-update-any-user","title":"5.1. Update any user","text":"{\n\"id\": \"4fd3477b-eccf-4ee3-8f7d-68ad72261476\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\ncurl \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-X PATCH \\\n-d \"{\\\"is_superuser\\\": true}\" \\\nhttp://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476\n
"},{"location":"usage/flow/#response_6","title":"Response","text":"axios.patch(\n'http://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476',\n{\nis_superuser: true,\n},\n{\nheaders: {\n'Authorization': `Bearer ${TOKEN}`,\n},\n},\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\n
"},{"location":"usage/flow/#52-delete-any-user","title":"5.2. Delete any user","text":"{\n\"id\": \"4fd3477b-eccf-4ee3-8f7d-68ad72261476\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": true\n}\ncurl \\\n-H \"Content-Type: application/json\" \\\n-H \"Authorization: Bearer $TOKEN\" \\\n-X DELETE \\\nhttp://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476\n
"},{"location":"usage/flow/#response_7","title":"Response","text":"axios.delete(\n'http://localhost:8000/users/4fd3477b-eccf-4ee3-8f7d-68ad72261476',\n{\nheaders: {\n'Authorization': `Bearer ${TOKEN}`,\n},\n},\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\ncurl \\\n-H \"Content-Type: application/json\" \\\n-H \"Cookie: fastapiusersauth=$TOKEN\" \\\n-X POST \\\nhttp://localhost:8000/auth/cookie/logout\n
"},{"location":"usage/flow/#response_8","title":"Response","text":"axios.post('http://localhost:8000/auth/cookie/logout',\nnull,\n{\nheaders: {\n'Cookie': `fastapiusersauth=${TOKEN}`,\n},\n}\n)\n.then((response) => console.log(response))\n.catch((error) => console.log(error));\nPOST /login","text":"name. Check the corresponding authentication method to view the success response.application/x-www-form-urlencoded)username=king.arthur@camelot.bt&password=guinevere\n422 Validation Error400 Bad Request{\n\"detail\": \"LOGIN_BAD_CREDENTIALS\"\n}\n400 Bad Request
"},{"location":"usage/routes/#post-logout","title":"{\n\"detail\": \"LOGIN_USER_NOT_VERIFIED\"\n}\nPOST /logout","text":"name. Check the corresponding authentication method to view the success response.401 Unauthorized200 OKPOST /register","text":"on_after_register handler on successful registration.{\n\"email\": \"king.arthur@camelot.bt\",\n\"password\": \"guinevere\"\n}\n201 Created{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\n422 Validation Error400 Bad Request{\n\"detail\": \"REGISTER_USER_ALREADY_EXISTS\"\n}\n400 Bad Request
"},{"location":"usage/routes/#reset-password-router","title":"Reset password router","text":""},{"location":"usage/routes/#post-forgot-password","title":"{\n\"detail\": {\n\"code\": \"REGISTER_INVALID_PASSWORD\",\n\"reason\": \"Password should be at least 3 characters\"\n}\n}\nPOST /forgot-password","text":"on_after_forgot_password handler if the user exists.202 Accepted response, even if the user requested does not exist.{\n\"email\": \"king.arthur@camelot.bt\"\n}\n202 AcceptedPOST /reset-password","text":"/forgot-password route.{\n\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI\",\n\"password\": \"merlin\"\n}\n200 OK422 Validation Error400 Bad Request{\n\"detail\": \"RESET_PASSWORD_BAD_TOKEN\"\n}\n400 Bad Request
"},{"location":"usage/routes/#verify-router","title":"Verify router","text":""},{"location":"usage/routes/#post-request-verify-token","title":"{\n\"detail\": {\n\"code\": \"RESET_PASSWORD_INVALID_PASSWORD\",\n\"reason\": \"Password should be at least 3 characters\"\n}\n}\nPOST /request-verify-token","text":"on_after_request_verify handler if the user exists, active and not already verified.202 Accepted response, even if the user requested does not exist, not active or already verified.{\n\"email\": \"king.arthur@camelot.bt\"\n}\n202 AcceptedPOST /verify","text":"/request-verify-token route. Will call the call the on_after_verify handler on success.{\n\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiOTIyMWZmYzktNjQwZi00MzcyLTg2ZDMtY2U2NDJjYmE1NjAzIiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTcxNTA0MTkzfQ.M10bjOe45I5Ncu_uXvOmVV8QxnL-nZfcH96U90JaocI\"\n}\n200 OK422 Validation Error400 Bad Request{\n\"detail\": \"VERIFY_USER_BAD_TOKEN\"\n}\n400 Bad Request
"},{"location":"usage/routes/#oauth-router","title":"OAuth router","text":"{\n\"detail\": \"VERIFY_USER_ALREADY_VERIFIED\"\n}\nGET /authorize","text":"
scopes: Optional list of scopes to ask for. Expected format: scopes=a&scopes=b.200 OK
"},{"location":"usage/routes/#get-callback","title":"{\n\"authorization_url\": \"https://www.tintagel.bt/oauth/authorize?client_id=CLIENT_ID&scopes=a+b&redirect_uri=https://www.camelot.bt/oauth/callback\"\n}\nGET /callback","text":"
code: OAuth callback code.state: State token.error: OAuth error.
associate_by_email flag is set to True on the router declaration, OAuth account is linked to the user. The user is authenticated following the chosen authentication method.
400 Bad Request400 Bad Request{\n\"detail\": \"OAUTH_NOT_AVAILABLE_EMAIL\"\n}\n400 Bad Request{\n\"detail\": \"OAUTH_USER_ALREADY_EXISTS\"\n}\n400 Bad Request
"},{"location":"usage/routes/#oauth-association-router","title":"OAuth association router","text":"{\n\"detail\": \"LOGIN_BAD_CREDENTIALS\"\n}\nGET /authorize","text":"
scopes: Optional list of scopes to ask for. Expected format: scopes=a&scopes=b.401 Unauthorized200 OK
"},{"location":"usage/routes/#get-callback_1","title":"{\n\"authorization_url\": \"https://www.tintagel.bt/oauth/authorize?client_id=CLIENT_ID&scopes=a+b&redirect_uri=https://www.camelot.bt/oauth/callback\"\n}\nGET /callback","text":"
code: OAuth callback code.state: State token.error: OAuth error.401 Unauthorized400 Bad Request400 Bad Request{\n\"detail\": \"OAUTH_NOT_AVAILABLE_EMAIL\"\n}\n200 OK
"},{"location":"usage/routes/#users-router","title":"Users router","text":""},{"location":"usage/routes/#get-me","title":"{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@tintagel.bt\",\n\"is_active\": true,\n\"is_superuser\": false,\n\"oauth_accounts\": [\n{\n\"id\": \"6c98caf5-9bc5-4c4f-8a45-a0ae0c40cd77\",\n\"oauth_name\": \"TINTAGEL\",\n\"access_token\": \"ACCESS_TOKEN\",\n\"expires_at\": \"1641040620\",\n\"account_id\": \"king_arthur_tintagel\",\n\"account_email\": \"king.arthur@tintagel.bt\"\n}\n]\n}\nGET /me","text":"200 OK{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\n401 UnauthorizedPATCH /me","text":"{\n\"email\": \"king.arthur@tintagel.bt\",\n\"password\": \"merlin\"\n}\n200 OK{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@tintagel.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\n401 Unauthorized400 Bad Request{\n\"detail\": {\n\"code\": \"UPDATE_USER_INVALID_PASSWORD\",\n\"reason\": \"Password should be at least 3 characters\"\n}\n}\n400 Bad Request{\n\"detail\": \"UPDATE_USER_EMAIL_ALREADY_EXISTS\"\n}\n
422 Validation Error
GET /{user_id}","text":"Return the user with id user_id.
200 OK
{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": true,\n\"is_superuser\": false\n}\n 401 Unauthorized
Missing token or inactive user.
403 Forbidden
Not a superuser.
404 Not found
The user does not exist.
"},{"location":"usage/routes/#patch-user_id","title":"PATCH /{user_id}","text":"Update the user with id user_id.
Payload
{\n\"email\": \"king.arthur@tintagel.bt\",\n\"password\": \"merlin\",\n\"is_active\": false,\n\"is_superuser\": true\n}\n 200 OK
{\n\"id\": \"57cbb51a-ab71-4009-8802-3f54b4f2e23\",\n\"email\": \"king.arthur@camelot.bt\",\n\"is_active\": false,\n\"is_superuser\": true\n}\n 401 Unauthorized
Missing token or inactive user.
403 Forbidden
Not a superuser.
404 Not found
The user does not exist.
400 Bad Request
Password validation failed.
{\n\"detail\": {\n\"code\": \"UPDATE_USER_INVALID_PASSWORD\",\n\"reason\": \"Password should be at least 3 characters\"\n}\n}\n 400 Bad Request
A user with this email already exists.
{\n\"detail\": \"UPDATE_USER_EMAIL_ALREADY_EXISTS\"\n}\n"},{"location":"usage/routes/#delete-user_id","title":"DELETE /{user_id}","text":"Delete the user with id user_id.
204 No content
401 Unauthorized
Missing token or inactive user.
403 Forbidden
Not a superuser.
404 Not found
The user does not exist.
"}]} \ No newline at end of file diff --git a/10.3/sitemap.xml b/10.3/sitemap.xml new file mode 100644 index 00000000..ae648a17 --- /dev/null +++ b/10.3/sitemap.xml @@ -0,0 +1,183 @@ + +FastAPI Users provides a dependency callable to easily inject authenticated user in your routes. They are available from your FastAPIUsers instance.
Tip
+For more information about how to make an authenticated request to your API, check the documentation of your Authentication method.
+current_user¶Return a dependency callable to retrieve currently authenticated user, passing the following parameters:
+optional: If True, None is returned if there is no authenticated user or if it doesn't pass the other requirements. Otherwise, throw 401 Unauthorized. Defaults to False.active: If True, throw 401 Unauthorized if the authenticated user is inactive. Defaults to False.verified: If True, throw 403 Forbidden if the authenticated user is not verified. Defaults to False.superuser: If True, throw 403 Forbidden if the authenticated user is not a superuser. Defaults to False.get_enabled_backends: Optional dependency callable returning a list of enabled authentication backends. Useful if you want to dynamically enable some authentication backends based on external logic, like a configuration in database. By default, all specified authentication backends are enabled. Please not however that every backends will appear in the OpenAPI documentation, as FastAPI resolves it statically.Create it once and reuse it
+This function is a factory, a function returning another function 🤯
+It's this returned function that will be the dependency called by FastAPI in your API routes.
+To avoid having to generate it on each route and avoid issues when unit testing, it's strongly recommended that you assign the result in a variable and reuse it at will in your routes. The examples below demonstrate this pattern.
+current_user = fastapi_users.current_user()
+
+@app.get("/protected-route")
+def protected_route(user: User = Depends(current_user)):
+ return f"Hello, {user.email}"
+current_active_user = fastapi_users.current_user(active=True)
+
+@app.get("/protected-route")
+def protected_route(user: User = Depends(current_active_user)):
+ return f"Hello, {user.email}"
+current_active_verified_user = fastapi_users.current_user(active=True, verified=True)
+
+@app.get("/protected-route")
+def protected_route(user: User = Depends(current_active_verified_user)):
+ return f"Hello, {user.email}"
+current_superuser = fastapi_users.current_user(active=True, superuser=True)
+
+@app.get("/protected-route")
+def protected_route(user: User = Depends(current_superuser)):
+ return f"Hello, {user.email}"
+Warning
+This is an advanced feature for cases where you have several authentication backends that are enabled conditionally. In most cases, you won't need this option.
+from fastapi import Request
+from fastapi_users.authentication import AuthenticationBackend, BearerTransport, CookieTransport, JWTStrategy
+
+SECRET = "SECRET"
+
+bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
+cookie_transport = CookieTransport(cookie_max_age=3600)
+
+def get_jwt_strategy() -> JWTStrategy:
+ return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
+
+jwt_backend = AuthenticationBackend(
+ name="jwt",
+ transport=bearer_transport,
+ get_strategy=get_jwt_strategy,
+)
+cookie_backend = AuthenticationBackend(
+ name="jwt",
+ transport=cookie_transport,
+ get_strategy=get_jwt_strategy,
+)
+
+async def get_enabled_backends(request: Request):
+ """Return the enabled dependencies following custom logic."""
+ if request.url.path == "/protected-route-only-jwt":
+ return [jwt_backend]
+ else:
+ return [cookie_backend, jwt_backend]
+
+
+current_active_user = fastapi_users.current_user(active=True, get_enabled_backends=get_enabled_backends)
+
+
+@app.get("/protected-route")
+def protected_route(user: User = Depends(current_active_user)):
+ return f"Hello, {user.email}. You are authenticated with a cookie or a JWT."
+
+
+@app.get("/protected-route-only-jwt")
+def protected_route(user: User = Depends(current_active_user)):
+ return f"Hello, {user.email}. You are authenticated with a JWT."
+If you don't need the user in the route logic, you can use this syntax:
+@app.get("/protected-route", dependencies=[Depends(current_superuser)])
+def protected_route():
+ return "Hello, some user."
+You can read more about this in FastAPI docs.
+ + + + + + +This page will present you a complete registration and authentication flow once you've setup FastAPI Users. Each example will be presented with a cURL and an axios example.
First step, of course, is to register as a user.
+You'll get a JSON response looking like this:
+{
+ "id": "4fd3477b-eccf-4ee3-8f7d-68ad72261476",
+ "email": "king.arthur@camelot.bt",
+ "is_active": true,
+ "is_superuser": false
+}
+Info
+Several things to bear in mind:
+User model (like a first name or a birthdate), you'll have to provide them in the payload.is_active or is_superuser itself at registration. Only a superuser can do it by PATCHing the user.Now, you can login as this new user.
+You can generate a login route for each authentication backend. Each backend will have a different response.
+const formData = new FormData();
+formData.set('username', 'king.arthur@camelot.bt');
+formData.set('password', 'guinevere');
+axios.post(
+ 'http://localhost:8000/auth/jwt/login',
+ formData,
+ {
+ headers: {
+ 'Content-Type': 'multipart/form-data',
+ },
+ },
+)
+.then((response) => console.log(response))
+.catch((error) => console.log(error));
+Warning
+Notice that we don't send it as a JSON payload here but with form data instead. Also, the email is provided by a field named username.
You'll get a JSON response looking like this:
+{
+ "access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM",
+ "token_type": "bearer"
+}
+You can use this token to make authenticated requests as the user king.arthur@camelot.bt. We'll see how in the next section.
const formData = new FormData();
+formData.set('username', 'king.arthur@camelot.bt');
+formData.set('password', 'guinevere');
+axios.post(
+ 'http://localhost:8000/auth/cookie/login',
+ formData,
+ {
+ headers: {
+ 'Content-Type': 'multipart/form-data',
+ },
+ },
+)
+.then((response) => console.log(response))
+.catch((error) => console.log(error));
+Warning
+Notice that we don't send it as a JSON payload here but with form data instead. Also, the email is provided by a field named username.
You'll get an empty response. However, the response will come with a Set-Cookie header (that's why we added the -v option in cURL to see them).
set-cookie: fastapiusersauth=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYzYwNjBmMTEtNTM0OS00YTI0LThiNGEtYTJhODc1ZGM1Mzk1IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4OTQ3fQ.qNA4oPVYhoqrJIk-zvAyEfEVoEnP156G30H_SWEU0sU; HttpOnly; Max-Age=3600; Path=/; Secure
+You can make authenticated requests as the user king.arthur@camelot.bt by setting a Cookie header with this cookie.
Tip
+The cookie backend is more suited for browsers, as they handle them automatically. This means that if you make a login request in the browser, it will automatically store the cookie and automatically send it in subsequent requests.
+Now that we can authenticate, we can get our own profile data. Depending on your authentication backend, the method to authenticate the request will vary. We'll stick with JWT from now on.
+export TOKEN="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM";
+curl \
+-H "Content-Type: application/json" \
+-H "Authorization: Bearer $TOKEN" \
+-X GET \
+http://localhost:8000/users/me
+const TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNGZkMzQ3N2ItZWNjZi00ZWUzLThmN2QtNjhhZDcyMjYxNDc2IiwiYXVkIjoiZmFzdGFwaS11c2VyczphdXRoIiwiZXhwIjoxNTg3ODE4NDI5fQ.anO3JR8-WYCozZ4_2-PQ2Ov9O38RaLP2RAzQIiZhteM';
+axios.get(
+ 'http://localhost:8000/users/me', {
+ headers: {
+ 'Authorization': `Bearer ${TOKEN}`,
+ },
+})
+.then((response) => console.log(response))
+.catch((error) => console.log(error));
+You'll get a JSON response looking like this:
+{
+ "id": "4fd3477b-eccf-4ee3-8f7d-68ad72261476",
+ "email": "king.arthur@camelot.bt",
+ "is_active": true,
+ "is_superuser": false
+}
+Tip
+If you use one of the dependency callable to protect one of your own endpoint, you'll have to authenticate exactly in the same way.
+We can also update our own profile. For example, we can change our password like this.
+You'll get a JSON response looking like this:
+{
+ "id": "4fd3477b-eccf-4ee3-8f7d-68ad72261476",
+ "email": "king.arthur@camelot.bt",
+ "is_active": true,
+ "is_superuser": false
+}
+Info
+Once again, the user cannot set is_active or is_superuser itself. Only a superuser can do it by PATCHing the user.
If you want to manage the users of your application, you'll have to become a superuser.
+The very first superuser can only be set at database level: open it through a CLI or a GUI, find your user and set the is_superuser column/property to true.
Now that you are a superuser, you can leverage the power of superuser routes. You can for example get the profile of any user in the database given its id.
+You'll get a JSON response looking like this:
+{
+ "id": "4fd3477b-eccf-4ee3-8f7d-68ad72261476",
+ "email": "king.arthur@camelot.bt",
+ "is_active": true,
+ "is_superuser": false
+}
+We can now update the profile of any user. For example, we can promote it as superuser.
+You'll get a JSON response looking like this:
+{
+ "id": "4fd3477b-eccf-4ee3-8f7d-68ad72261476",
+ "email": "king.arthur@camelot.bt",
+ "is_active": true,
+ "is_superuser": true
+}
+Finally, we can delete a user.
+You'll get an empty response.
+We can also end the session.
+You'll get an empty response.
+That's it! You now have a good overview of how you can manage the users through the API. Be sure to check the Routes page to have all the details about each endpoints.
+ + + + + + +You'll find here the routes exposed by FastAPI Users. Note that you can also review them through the interactive API docs.
+Each authentication backend you generate a router for will produce the following routes. Take care about the prefix you gave it, especially if you have several backends.
+POST /login¶Login a user against the method named name. Check the corresponding authentication method to view the success response.
Payload (application/x-www-form-urlencoded)
422 Validation Error
400 Bad Request
Bad credentials or the user is inactive.
+ +POST /logout¶Logout the authenticated user against the method named name. Check the corresponding authentication method to view the success response.
401 Unauthorized
Missing token or inactive user.
+200 OK
The logout process was successful.
+POST /register¶Register a new user. Will call the on_after_register handler on successful registration.
201 Created
422 Validation Error
400 Bad Request
A user already exists with this email.
+ +400 Bad Request
Password validation failed.
+ +POST /forgot-password¶Request a reset password procedure. Will generate a temporary token and call the on_after_forgot_password handler if the user exists.
To prevent malicious users from guessing existing users in your database, the route will always return a 202 Accepted response, even if the user requested does not exist.
202 Accepted
POST /reset-password¶Reset a password. Requires the token generated by the /forgot-password route.
Payload
+ +200 OK
422 Validation Error
400 Bad Request
Password validation failed.
+ +POST /request-verify-token¶Request a user to verify their e-mail. Will generate a temporary token and call the on_after_request_verify handler if the user exists, active and not already verified.
To prevent malicious users from guessing existing users in your database, the route will always return a 202 Accepted response, even if the user requested does not exist, not active or already verified.
202 Accepted
POST /verify¶Verify a user. Requires the token generated by the /request-verify-token route. Will call the call the on_after_verify handler on success.
Payload
+ +200 OK
422 Validation Error
400 Bad Request
Bad token, not existing user or not the e-mail currently set for the user.
+ +400 Bad Request
The user is already verified.
+ +Each OAuth router you define will expose the two following routes.
+GET /authorize¶Return the authorization URL for the OAuth service where you should redirect your user.
+Query parameters
+scopes: Optional list of scopes to ask for. Expected format: scopes=a&scopes=b.200 OK
GET /callback¶Handle the OAuth callback.
+Query parameters
+code: OAuth callback code.state: State token.error: OAuth error.Depending on the situation, several things can happen:
+associate_by_email flag is set to True on the router declaration, OAuth account is linked to the user. The user is authenticated following the chosen authentication method.400 Bad Request
Invalid token.
+400 Bad Request
The OAuth provider didn't return an e-mail address. Make sure this provider return e-mail address through their API and you have asked for the required scope.
+ +400 Bad Request
Another user with the same e-mail address already exists.
+ +Each OAuth association router you define will expose the two following routes.
+GET /authorize¶Return the authorization URL for the OAuth service where you should redirect your user.
+Query parameters
+scopes: Optional list of scopes to ask for. Expected format: scopes=a&scopes=b.401 Unauthorized
Missing token or inactive user.
+200 OK
GET /callback¶Handle the OAuth callback and add the OAuth account to the current authenticated active user.
+Query parameters
+code: OAuth callback code.state: State token.error: OAuth error.401 Unauthorized
Missing token or inactive user.
+400 Bad Request
Invalid token.
+400 Bad Request
The OAuth provider didn't return an e-mail address. Make sure this provider return e-mail address through their API and you have asked for the required scope.
+ +200 OK
{
+ "id": "57cbb51a-ab71-4009-8802-3f54b4f2e23",
+ "email": "king.arthur@tintagel.bt",
+ "is_active": true,
+ "is_superuser": false,
+ "oauth_accounts": [
+ {
+ "id": "6c98caf5-9bc5-4c4f-8a45-a0ae0c40cd77",
+ "oauth_name": "TINTAGEL",
+ "access_token": "ACCESS_TOKEN",
+ "expires_at": "1641040620",
+ "account_id": "king_arthur_tintagel",
+ "account_email": "king.arthur@tintagel.bt"
+ }
+ ]
+}
+GET /me¶Return the current authenticated active user.
+200 OK
401 Unauthorized
Missing token or inactive user.
+PATCH /me¶Update the current authenticated active user.
+ +200 OK
401 Unauthorized
Missing token or inactive user.
+400 Bad Request
Password validation failed.
+ +400 Bad Request
A user with this email already exists. +
+422 Validation Error
GET /{user_id}¶Return the user with id user_id.
200 OK
401 Unauthorized
Missing token or inactive user.
+403 Forbidden
Not a superuser.
+404 Not found
The user does not exist.
+PATCH /{user_id}¶Update the user with id user_id.
Payload
+ +200 OK
401 Unauthorized
Missing token or inactive user.
+403 Forbidden
Not a superuser.
+404 Not found
The user does not exist.
+400 Bad Request
Password validation failed.
+ +400 Bad Request
A user with this email already exists. +
+DELETE /{user_id}¶Delete the user with id user_id.
204 No content
401 Unauthorized
Missing token or inactive user.
+403 Forbidden
Not a superuser.
+404 Not found
The user does not exist.
+