FastAPI - Security

  • FastAPI provides several tools to help you deal with Security easily, rapidly, in a standard way, without having to study and learn all the security specifications.

    Introducció

    Hash password

    Argon2 is a modern, secure password hashing algorithm and winner of the 2015 Password Hashing Competition. It’s memory-hard and resists brute-force, side-channel, and precomputation attacks, making it the top choice for securing passwords in modern systems.

    Terminal window
    uv add argon2-cffi
    from argon2 import PasswordHasher
    ph = PasswordHasher()
    res = ph.hash("MySecurePassword")
    print(res)

    To check whether a user-entered password matches the stored hash:

    from argon2 import PasswordHasher
    ph = PasswordHasher()
    res = ph.hash("MySecurePassword")
    try:
    ph.verify(res, "MySecurePassword")
    print("Password match!")
    except Exception:
    print("Incorrect password.")

    Bearer authentication

    Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens. The name “Bearer authentication” can be understood as “give access to the bearer of this token.” The bearer token is a cryptic string, usually generated by the server in response to a login request. The client must send this token in the Authorization header when making requests to protected resources:

    Authorization: Bearer <token>

    Swagger - Bearer Authentication

    Simple OAuth2 with Password and Bearer

    JWT

    JWT means “JSON Web Tokens”.

    It’s a standard to codify a JSON object in a long dense string without spaces. It looks like this:

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

    It is not encrypted, so anyone could recover the information from the contents.

    But it’s signed. So, when you receive a token that you emitted, you can verify that you actually emitted it.

    That way, you can create a token with an expiration of, let’s say, 1 week. And then when the user comes back the next day with the token, you know that user is still logged in to your system.

    After a week, the token will be expired, and the user will not be authorized and will have to sign in again to get a new token. And if the user (or a third party) tried to modify the token to change the expiration, you would be able to discover it, because the signatures would not match.

    If you want to play with JWT tokens and see how they work, check https://jwt.io.

    Nota

    If you are planning to use digital signature algorithms like RSA or ECDSA, you should install the cryptography library dependency pyjwt[crypto].

    You can read more about it in the PyJWT Installation docs.

    OAuth2 with Password (and hashing), Bearer with JWT tokens

    Pendent