0
0
FastAPIframework~5 mins

OAuth2 password flow in FastAPI

Choose your learning style9 modes available
Introduction

OAuth2 password flow lets users log in by giving their username and password directly to your app. It helps your app get a token to access protected data safely.

When building a trusted app where users enter their username and password directly.
When you want to get an access token to call APIs on behalf of the user.
When you need a simple login system without redirecting users to external login pages.
When you control both the client app and the authentication server.
When you want to test authentication quickly during development.
Syntax
FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    username = form_data.username
    password = form_data.password
    # Verify username and password here
    # Return access token if valid
    return {'access_token': 'token123', 'token_type': 'bearer'}

Use OAuth2PasswordRequestForm to get username and password from form data.

The endpoint usually returns a JSON with access_token and token_type.

Examples
Simple example returning a token based on username.
FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    return {'access_token': form_data.username + '_token', 'token_type': 'bearer'}
Example with simple username and password check and error handling.
FastAPI
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    if form_data.username != 'user' or form_data.password != 'pass':
        raise HTTPException(status_code=400, detail='Incorrect username or password')
    return {'access_token': 'securetoken123', 'token_type': 'bearer'}
Sample Program

This FastAPI app has a /token endpoint that accepts username and password using OAuth2 password flow. It checks the username and password against a fake database. If correct, it returns an access token. If not, it returns an error.

FastAPI
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.responses import JSONResponse

app = FastAPI()

fake_users_db = {
    'alice': 'wonderland123',
    'bob': 'builder456'
}

@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    username = form_data.username
    password = form_data.password
    if username not in fake_users_db or fake_users_db[username] != password:
        raise HTTPException(status_code=400, detail='Incorrect username or password')
    token = f'{username}_token_abc123'
    return {'access_token': token, 'token_type': 'bearer'}
OutputSuccess
Important Notes

Never use OAuth2 password flow in apps you don't fully control because users share their passwords.

Always use HTTPS to protect username and password during transmission.

In real apps, verify passwords securely and generate real tokens (like JWT).

Summary

OAuth2 password flow lets users log in by sending username and password to your app.

FastAPI provides OAuth2PasswordRequestForm to handle this easily.

Use this flow only in trusted apps and always protect user data carefully.