OAuth2 Password Flow: Trading Credentials for a Token

The OAuth2 Password Flow trades a user's credentials for a temporary access token. It's used in trusted first-party apps, like a mobile app logging into its own backend, to avoid sending a password with every API call.
WHY IT EXISTS The OAuth2 Password Flow was created to give an application's own trusted clients, like its official mobile app, a simple way to get an access token. It avoids the complex browser redirects of other flows by centralizing authentication at a single API endpoint where the client can directly post credentials.
THE MENTAL MODEL Think of it like a coat check for your credentials. You give the attendant (the token endpoint) your username and password (your coat). They verify you and give you a ticket (the access token). For the rest of the night, you show the ticket to access different areas (protected API endpoints), not your original coat. You never give your coat to anyone but the official attendant.
HOW IT WORKS The client application makes a POST request to a dedicated token endpoint, like /token. The body of this request contains the grant_type set to "password", along with the user's username and password. The server validates these credentials. If correct, it generates a short-lived access token and returns it to the client. The client then includes this token in the Authorization header of all future requests, typically as a "Bearer" token.
WHEN TO USE IT This flow should only be used when the client application is fully trusted and controlled by the same organization as the server. Common examples include a company's official first-party mobile app or a single-page web application communicating with its own backend API. In these cases, the user is entering their password into an interface they trust.
WHEN NOT TO USE IT Never use the Password Flow for third-party applications. It requires the user to share their password directly with the client app, which is a major security vulnerability. If that app is compromised, the user's credentials are stolen. The IETF now considers this flow a legacy practice and strongly recommends against it for new applications, favoring the Authorization Code Flow with PKCE instead.
ONE CANONICAL EXAMPLE In FastAPI, you define a /token path operation that accepts data from an OAuth2PasswordRequestForm. This form dependency extracts the username and password. You then write logic to authenticate the user. If successful, you create an access token (often a JWT) and return it in a JSON response, like {"access_token": "...", "token_type": "bearer"}. Other endpoints are then protected with a dependency that validates this Bearer token.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.