Security - Simple OAuth2
Implement OAuth2 password flow with form data authentication
Simple OAuth2 with Password and Bearer
🎯 What You'll Learn
- Implement OAuth2 password flow with form data authentication
- Use OAuth2PasswordRequestForm for handling login credentials
- Create token endpoints that return access tokens
- Build complete authentication flow with user validation
📚 Theory
Now let's build from the previous chapter and add the missing parts to have a complete security flow.
Get the username
and password
We are going to use FastAPI security utilities to get the username
and password
.
OAuth2 specifies that when using the "password flow" (that we are using) the client/user must send a username
and password
fields as form data.
And the spec says that the fields have to be named like that. So user-name
or email
wouldn't work.
But don't worry, you can show it as you wish to your final users in the frontend. And your database models can use any other names you want.
But for the login path operation, we need to use these names to be compatible with the spec (and be able to, for example, use the integrated API documentation system).
The spec also states that the username
and password
must be sent as form data (so, no JSON here).
Code to get the username
and password
Now let's use the utilities provided by FastAPI to handle this:
from fastapi.security import OAuth2PasswordRequestForm
@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
user_dict = fake_users_db.get(form_data.username)
if not user_dict:
raise HTTPException(status_code=400, detail="Incorrect username or password")
# ... validate password and return token
The OAuth2PasswordRequestForm
is a class dependency that declares a form body with:
- The
username
- The
password
- An optional
scope
field as a big string, composed of strings separated by spaces - An optional
grant_type
🔧 Key Concepts
- Form Data Authentication: OAuth2 password flow requires form data, not JSON
- Token Endpoint: Returns access tokens in standardized format
- Password Verification: Check hashed passwords (never store plaintext)
- User Status: Verify user is active before granting access
- Bearer Tokens: Use "Bearer" token type for authorization headers
💡 Best Practices
- Always hash passwords, never store plaintext
- Return consistent error messages for security
- Include WWW-Authenticate header for 401 responses
- Validate user is active before granting access
- Use proper OAuth2 response format
🔗 Additional Resources
💡 Hint
Remember to use form data (not JSON) for OAuth2 password flow and return the correct token response format
Ready to Practice?
Now that you understand the theory, let's put it into practice with hands-on coding!
Start Interactive Lesson