Files
François Voron c4de66b81c Revamp authentication (#831)
* Implement Transport classes

* Implement authentication strategy classes

* Revamp authentication with Transport and Strategy

* Revamp strategy and OAuth so that they can use a callable dependency

* Update docstring

* Make ErrorCode a proper Enum and cleanup unused OpenAPI utils

* Remove useless check

* Tweak typing in authenticator

* Update docs

* Improve logout/destroy token logic

* Update docs

* Update docs

* Update docs and full examples

* Apply formatting to examples

* Update OAuth doc and examples

* Add migration doc

* Implement Redis session token

* Add Redis Session documentation

* RedisSession -> Redis

* Fix links in docs
2021-12-30 15:22:07 +01:00

2.3 KiB

Authentication

FastAPI Users allows you to plug in several authentication methods.

How it works?

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 HTTPException is raised.

For each backend, you'll be able to add a router with the corresponding /login and /logout. More on this in the routers documentation.

Transport + Strategy = Authentication backend

An authentication backend is composed of two parts:

Transport

It manages how the token will be carried over the request. We currently provide two methods:

Bearer

The token will be send through an Authorization: Bearer header.

!!! tip "Pros and cons"

* ✅ Easy to read and set in every requests.
* ❌ Needs to be stored manually somewhere in the client.

➡️ Use it if you want to implement a mobile application or a pure REST API.

Cookie

The token will be send through a cookie.

!!! tip "Pros and cons"

* ✅ Automatically stored and sent securely by web browsers in every requests.
* ✅ Automatically removed at expiration by web browsers.
* ❌ Needs a CSRF protection for maximum security.
* ❌ Harder to work with outside a browser, like a mobile app or a server.

➡️ Use it if you want to implement a web frontend.

Strategy

It manages how the token is generated and secured. We currently provide two methods:

JWT

The token is self-contained in a JSON Web Token.

!!! tip "Pros and cons"

* ✅ Self-contained: it doesn't need to be stored in a database.
* ❌ Can't be invalidated on the server-side: it's valid until it expires.

➡️ Use it if you want to get up-and-running quickly.

Redis

The token is stored in a Redis key-store.

!!! tip "Pros and cons"

* ✅ Secure and performant.
* ✅ Tokens can be invalidated server-side by removing tokens from Redis.
* ❌ A Redis server is needed.

➡️ Use it if you want maximum performance while being able to invalidate tokens.