October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Add Authentication and Permissions to a FastAPI Application

Learn how to add bearer-token authentication, a reusable current-user dependency, and route-level permission checks to a FastAPI application.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To protect a FastAPI endpoint, first authenticate the caller—validate a credential and resolve it to a current user—then authorize the requested action. FastAPI’s security dependencies provide the building blocks: a bearer-token dependency can document your token URL in OpenAPI, a shared dependency can load the user, and route-level checks can enforce permissions. Use OAuth2 scopes when their standardized grants and API documentation are useful; for simple rules such as “owner or administrator,” ordinary application logic is often clearer.

Authentication and authorization are separate checks

Authentication establishes who is making the request. For a bearer-token API, that means validating the token and resolving its subject to a user in your application. Authorization decides whether that authenticated user may perform a particular operation or access a particular resource.

As an Amazon Associate I earn from qualifying purchases.

A token’s presence alone proves neither identity nor permission. A secure request path validates the credential, checks that the associated account is usable, and then evaluates the permission required for the route or resource.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start with FastAPI’s bearer-token dependency

OAuth2PasswordBearer extracts a bearer token from the request’s Authorization header and adds an OAuth2 security scheme to the generated OpenAPI document. Its tokenUrl describes the URL clients should use to obtain a token; it does not create that endpoint. FastAPI’s first steps guide explains this distinction.

#1 Best Overall
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Use a relative token URL when appropriate, such as token rather than a hard-coded host and path. Relative URLs allow the documented endpoint to resolve correctly when the application is mounted under a prefix or served behind a proxy prefix.

Create a token endpoint and reusable current-user dependency

Verify credentials and issue a token

Your token endpoint should look up the submitted account and verify the submitted password against a stored password hash. Never store or compare plaintext passwords. The official FastAPI walkthrough uses pwdlib for password hashing and PyJWT for JSON Web Token operations; treat these as the packages used in that example, and confirm their current guidance and compatibility with your project’s pinned versions.

Rank #2
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

After successful verification, return a short-lived access token containing an expected subject that identifies the user. The official OAuth2 with Password (and hashing), Bearer with JWT tokens guide demonstrates the flow. Its example key and in-memory user records are illustrative only: use managed secret handling and your application’s real user store rather than copying them into a deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Validate the token and resolve the user

Make one dependency responsible for decoding and validating the token, requiring the expected subject claim, and loading that subject from your data store. Reject absent, malformed, expired, or otherwise invalid credentials with an authentication error, and reject a subject that does not map to a current user. Keep response models separate from persistence records so password hashes and other private fields are never returned to clients.

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

If accounts have states such as active or disabled, include an active-user check in the dependency chain. The FastAPI JWT walkthrough demonstrates rejecting an inactive user. This central approach lets protected routes depend on one trusted current-user result rather than repeating token parsing and account lookup.

Enforce permissions where operations are declared

Authentication alone does not authorize an operation. Place the authorization check at the route or resource boundary where the required permission is known. For domain-specific conditions—such as whether a user owns a particular record—check the relevant resource relationship in application code.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

For example, a route that reads a user record might require users:read, while a route that changes one might require users:write. These names are conventions your application defines; a colon has no built-in OAuth2 meaning.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use OAuth2 scopes when they add value

FastAPI can declare scopes in the OAuth2 scheme and attach route requirements with Security(..., scopes=[...]). A shared dependency can receive SecurityScopes, which exposes the requirements accumulated through the dependency tree. The dependency must compare every required scope with the authenticated principal’s grants and deny the request when a grant is missing. Declaring a scope documents a requirement; it does not enforce it by itself.

Best Value
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified (Pack of 2)
  • The information below is per-pack only
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.

The OAuth2 scopes guide describes scopes as optional: “You don’t necessarily need OAuth2 scopes, and you can handle authentication and authorization however you want.” It also cautions that scopes can be overkill and that enforcement still belongs in application code.

Scopes are a good fit when permissions map naturally to OAuth2 grants, third-party clients need delegated access, or publishing route requirements in OpenAPI helps clients understand the API. They are less useful when each rule is a domain relationship, such as “owner or administrator,” or when a small internal application would gain more ceremony than clarity. Keep those checks in application logic unless a scope vocabulary genuinely helps.

Choose an identity and permission model that fits the clients

Decision Prefer this when Trade-off to account for
Application-owned username and password A frontend you control submits credentials to your backend, and your application is responsible for account handling. Your application must securely manage password verification, account state, and token issuance.
External OAuth2 identity provider You are integrating third-party clients, need delegated access, or prefer to delegate login and identity lifecycle. The flow must match the client and provider; integration and operational requirements move partly to that provider.
Application authorization checks Rules are simple, domain-specific, or based on ownership and roles. Requirements may be less standardized in OpenAPI than explicit scope declarations.
OAuth2 scopes Grants are stable, map to delegated permissions, and benefit from OpenAPI documentation. Application code still has to grant and enforce scopes; adopting them for every domain rule can add needless complexity.

The password flow in FastAPI’s tutorial is an example for an application whose own frontend submits a username and password to its backend, not a universal choice for every OAuth2 integration. If you are building an OAuth2 provider or serving third-party clients, select a flow appropriate to those clients rather than assuming the tutorial’s flow applies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the authorization boundary, not just token creation

Exercise each protected route with cases that cover both identity and permission decisions:

  • No token, a malformed token, and an expired token should fail authentication.
  • A token for a disabled account should be rejected if your application enforces account state.
  • A valid token without a required permission should fail authorization.
  • A valid token with the required permission should reach the operation.

Choose the response mapping required by your API: missing or invalid authentication should produce an authentication challenge, while an authenticated user who lacks permission should be treated as an authorization failure. Keep error details generic enough not to reveal sensitive account information. The precise policy depends on the application and its threat model.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.