Articles · Cybersecurity · Authentication · FastAPI · JWT · Python · RBAC
How Token-Based Authentication Really Works: JWTs, Refresh Tokens and Roles
Secure Authentication with JWTs, Refresh Tokens and Roles

Why Authentication Needs More Thought Than I Expected
When I first learned about authentication, it seemed simple: the user types an email and password, the server checks them, and the user gets in. Building a real service showed me that this is only the first step. The backend also has to keep passwords safe, hand out credentials that are hard to fake, deal with tokens that expire or get stolen, and stop logged-in users from doing things they aren't allowed to do.
For Project 1, I built a reusable Authentication and Authorization Service with FastAPI and PostgreSQL. It covers registration and login, password hashing, JWT access tokens, refresh-token rotation, role-based access control (RBAC), API keys, security audit events, and protection against repeated login attempts. Redis handles two jobs: short-lived rate-limit data and instantly revoking access tokens.

1. Passwords: Hash Them, Never Store Them
A server should never keep the actual password a user chose. If a database backup leaks and the passwords are in plain text, every account is exposed at once. So the service stores a hash instead. At login, it checks the submitted password against that hash. Hashing only works in one direction, so the app can verify a password without ever being able to recover it.
I used Argon2id through the argon2-cffi library. It was built for passwords, and its memory and processing costs can be tuned so that every guess takes real effort. A hash like SHA-256 is fast on purpose, which is exactly the wrong property here. An attacker holding stolen hashes could try guesses very quickly.
Every password also gets its own random salt, so two users with the same password still end up with different hashes. The library takes care of the salt and keeps the parameters needed for verification alongside the hash. So at registration, the service validates the input, hashes the password and saves the hash. At login, it verifies the password against the saved hash.
Another detail is that the login error should never reveal whether an email is registered. If the API says "email not found" in one case and "wrong password" in another, an attacker can use that to work out who has an account. My service returns the same generic failure for both. I also tried to keep the password check taking about the same time whether or not the user exists. These steps cut down on information leaks, but they don't rule out every possible way of discovering accounts.
2. How JWT Access Tokens Work
Once a user logs in, the client needs something to send with later requests. A JSON Web Token (JWT) is a compact way to carry claims about the user and about the token itself. It has three parts: a header (the token type and signing algorithm), a payload (the claims), and a signature that lets the server detect any tampering.
My access tokens carry the subject (sub), expiry (exp), issue time (iat), a unique token ID (jti) and the user's roles. One thing worth remembering is that a signed JWT is not encrypted. The payload is just encoded, so anyone can read it. Passwords and private data should never go inside one.
I went with RS256. The service signs tokens with an RSA private key, and anyone with the matching public key can verify them. That helps when several services need to check tokens, because a verifier doesn't need the private key that creates them. HS256 is different. It uses one shared secret for both signing and verifying, so anything that knows the secret can also create valid tokens.
The verifier must decide up front which algorithm it accepts, then check the signature and expiry. It should never just follow whatever algorithm an untrusted token claims to use. In my service, an authentication dependency reads the Bearer token from the Authorization header, validates it, and sets the identity for the request. A missing, expired or invalid token gets an HTTP 401 Unauthorized.
3. Why Both Access and Refresh Tokens?
Access tokens are sent to protected endpoints all the time, so they should be short-lived. Mine expire after 15 minutes. That limits the damage if one is stolen, but making users type their password every 15 minutes would be miserable.
That's what refresh tokens are for. They let the client get a new access token without a fresh login. Mine last seven days. Because a refresh token can keep producing new access tokens, it's a sensitive credential and needs more protection than just sitting in a database.
The service generates a random refresh-token value and stores only its hash in PostgreSQL. If the database leaks, the stored records can't be used directly as tokens. When a client presents a token, the service compares it with the stored record and checks its state.
Refresh tokens are also rotated. After a successful refresh, the user gets a new access token and a new refresh token, and the old refresh token is marked as used. The client has to replace the old one. If a used token shows up again, that suggests it was copied or stolen, so the service detects the reuse and can revoke the whole token family, which stops the compromised session from refreshing.
Concurrency was another issue. Two requests with the same token can arrive almost at once, and without coordination both might succeed. I used database row locking on that operation so only one request can consume the token.
Logout isn't stateless in this design. The service revokes the refresh token, and Redis holds the revoked access-token jti values until they would have expired anyway. This lets an access token be cut off immediately instead of waiting out its natural expiry, depending on the validation path and on Redis being available. That also means Redis health and failure behavior matter for the running service.
4. Authentication vs. Authorization
Authentication answers "who is making this request?" Authorization answers "what is this person allowed to do?" A user can hold a perfectly valid token and still not be allowed into an admin endpoint.
The service uses RBAC with roles like user, admin and service. Endpoints can require a certain role, and the authorization dependency checks the user's roles before allowing the action. Admin actions such as listing users, assigning roles or disabling accounts have to be locked down so nobody can promote themselves.
The status codes reflect the same split. A 401 means valid credentials are missing or unacceptable, such as a token that is absent, expired or invalid. A 403 means the user is authenticated but not permitted to do that action. Keeping these two clear helps API clients react correctly, and it makes access-control tests easier to read.
5. API Keys for Service-to-Service Calls
Not every caller is a person in a browser or an app. Backend services sometimes need to call specific endpoints directly, and API keys are one way to authenticate them.
In this project, keys are random values. The raw key is displayed only once, when it's created. The database keeps a hash and a short prefix for identification. Each key can have a name, scopes and an optional expiry. Scopes define what the key may do, and revocation lets an admin or owner switch off a key that's no longer needed.
6. Brute-Force Protection and Audit Events
A public login endpoint will get repeated password guesses. Rate limiting slows down automated guessing and password spraying by limiting how fast failed attempts can happen. But a plain account-wide lockout has its own problem. An attacker could trigger it on purpose and stop the real user from logging in. So instead of permanently disabling accounts in PostgreSQL after failures, I used a few Redis-based controls.
Tier 1: five failed attempts from one IP against one account lock that IP and account pair for 15 minutes.
Tier 2: 20 failed attempts from one IP across different accounts lock that IP for 15 minutes, which catches spraying.
Tier 3: 15 failures against one account from multiple IPs trigger a short cooldown on that account.
This adds friction for attackers without locking real users out for good. It reduces a common lockout risk, but it doesn't make denial-of-service attacks impossible.
Security audit events record relevant activity, such as authentication failures and credential or account-management actions the service supports. Logs are only useful if they don't become another place for secrets to leak. So passwords, raw access tokens, refresh tokens and API keys are never written into them. I describe this as security audit logging. It does not claim to be hash-chained or tamper-evident.
7. Security Headers and Testing the Unhappy Paths
Security also depends on how the API responds. The service sets X-Content-Type-Options, X-Frame-Options, Referrer-Policy and Permissions-Policy, and uses Content-Security-Policy rules for API responses and the interactive docs pages. HSTS is added only when HTTPS is actually in use or explicitly enforced, so local plain-HTTP development doesn't leave browsers with unwanted HTTPS restrictions. The outdated X-XSS-Protection header is set to 0 to turn off the old browser filter. I don't treat it as a replacement for a proper content security policy.
Testing a successful login isn't enough for this kind of service. The tests also need to cover expired tokens, altered signatures, wrong algorithms, missing credentials, insufficient roles, refresh-token reuse and concurrent refreshes. My latest pytest run finished with 69 tests passed and none failed. The suite covers authentication and input validation, RBAC, JWT signatures, refresh rotation and reuse detection, API-key hashing and revocation, brute-force controls, security headers, health checks and the specification matrix.
I also used Bandit to scan the Python code for common security issues and pip-audit to check installed dependencies against known vulnerabilities. The latest run showed zero Bandit findings and no known vulnerable packages. That's good evidence, but it isn't proof that the app has no vulnerabilities, because these tools only catch what their checks and data cover.
8. Running It and What I Learned Along the Way
I ran everything locally with Docker Compose. The app, PostgreSQL and Redis containers all came up healthy. The API is on port 8001 because another project of mine was already using 8000. Through the Swagger UI at http://localhost:8001/docs, I tested registration, login and the protected profile endpoint. Registration returned the new profile with the default role. Login returned an access token and a refresh token. After I added the Bearer token, GET /me returned the authenticated user's profile. No live credentials appear in this article.
Some details took more effort than the endpoint design itself. The container health checks had to wait for the services they depended on, refresh rotation needed a database lock to handle concurrency, and CI had to respect its configured environment. It showed me that security isn't only about cryptographic algorithms. Deployment setup, database transaction behavior and repeatable tests matter just as much.
9. Limitations and Future Improvements
This project shows the core authentication and authorization patterns, but it isn't a full identity-management platform. Multi-factor authentication isn't implemented, and email verification is postponed. The app expects HTTPS to be handled by the deployment environment or a reverse proxy in front of it. The RSA private keys are loaded from local PEM files instead of a hardware security module or a cloud key-management service.
Conclusion
Building this made me see authentication as a lifecycle rather than just a login endpoint. It covers password storage, creating and verifying tokens, renewing them, revoking them, checking roles, and handling failures safely. Argon2id protects stored passwords. Short-lived RS256 JWTs authenticate requests. Refresh-token rotation helps catch reuse. RBAC separates identity from permission. Hashed API keys let services connect without storing reusable raw credentials.
The biggest lesson was to design for failure as carefully as for success. Tokens can be stolen, replayed, expired or tampered with. Two refresh requests can race each other. A login endpoint can be attacked from one IP or many. Tests, static analysis, dependency checks and CI keep these protections working as the code changes, and honest documentation keeps the limitations visible.
The source code, setup instructions and tests are in the repository: https://github.com/HariniMurali04/authentication-authorization-service.
Comments
Loading comments…