Sub topic 14
Sessions, devices and API keys
Earlier chapters covered the login: passwords, authenticator codes and passkeys. This chapter covers what happens after the login. An exchange issues you a session, remembers your devices, and may hand out API keys. Each of these is a credential, and a strong login does not protect them once they exist.
This chapter assumes you have enrolled an authenticator app or a passkey, and that you know what a cookie and an HTTP request are. You do not need to write code, but one example uses Python.
Why the login is not the only door
You prove your identity once, and the exchange then gives your browser a session token. This is usually a random string stored in a cookie. On every later request the browser sends the token, and the server treats the request as coming from you. It does not ask for your password or second factor again.
That design has a consequence. Whoever holds the token is you, for as long as the token is valid. A stolen token needs no password, no code and no passkey.
The common ways tokens leak:
- Infostealer malware. Malware on your computer copies cookies and saved logins from browser profiles and uploads them to the attacker.
- Malicious browser extensions. An extension with permission to read site data can read session cookies or alter pages.
- Adversary-in-the-middle phishing. A fake site proxies your real login, relays your password and one-time code to the real exchange, and keeps the session token the exchange returns.
- Shared or public computers. A session left open on a borrowed machine stays usable.
Note where passkeys help and where they do not. A passkey blocks the proxy-phishing path, because the browser will not sign a challenge for a fake origin. It does not stop malware that already runs on your device and copies the cookie afterward. Hardening the device is a separate job.
What exchanges do about sessions
Exchanges limit the damage from stolen tokens in several ways. Which ones exist differs by exchange, so check your settings rather than assuming.
| Control | What it does | Limit |
|---|---|---|
| Session expiry | Tokens stop working after a set time or inactivity | A thief has a window of hours or days |
| Device list | Shows each browser or app that has logged in | Only useful if you look at it |
| Remote logout | Revokes one or all sessions | Does not remove API keys |
| Re-authentication | Asks for a passkey or code again for sensitive actions | Depends on the exchange applying it to withdrawals |
| New-device alerts | Email or push message on a login from an unknown device | Useless if the attacker also controls your email |
Re-authentication matters most. If the exchange demands a fresh second factor for each withdrawal, address change or API key creation, a stolen session token alone cannot move your funds. If it does not, the session token is nearly as powerful as your credentials. Look for settings that tie these actions to a fresh factor, and turn them on.
Device hygiene
Because the session lives on your device, the device is part of your security boundary. A practical baseline:
- Keep the operating system and browser updated. Many infostealers use known, already-patched flaws.
- Use a separate browser profile for the exchange. Install no extensions in it, or only ones you fully trust. This shrinks the set of code that can read your cookies.
- Do not install cracked software, game mods or "trading tools" from unofficial sources. These are the usual delivery route for infostealers.
- Log out on any device you do not own, and do not tick "remember this device" there.
- Use a device lock (PIN, biometric, full-disk encryption) so a lost laptop or phone does not hand over open sessions.
- Keep the authenticator app on a different device from the exchange sessions when you can. If one device is compromised, the attacker does not get both.
API keys are separate credentials
An API key lets a program act on your account without a browser, for example a trading bot, a portfolio tracker or a tax tool. A key usually has two parts: a public key ID, and a secret used to sign requests. Three facts shape how you should handle them:
- API access often skips your login factors. The key and secret are the credential. No passkey or authenticator code is asked for on each request.
- Keys outlive password changes on many exchanges. Resetting your password may not revoke existing keys. Check this on your exchange and remove keys by hand.
- Permissions are chosen when you create the key. The exchange cannot tell whether a request came from your bot or from a thief holding the same secret.
Least privilege
When you create a key, grant only what the program needs:
- Read-only for trackers and tax tools. A leaked read-only key exposes your balances and history but cannot move money.
- Trading only for bots that place orders. Leave withdrawals off.
- Withdrawal permission almost never. If you must enable it, restrict it to allowlisted addresses and an IP allowlist, and keep the key short-lived.
A trade-only key is not harmless. An attacker with it can still place a series of bad trades, for example buying a thinly traded token at inflated prices from an account they control on the other side. Treat trade permission as real risk, and limit the funds in the account the bot uses.
Restrict where the key works
Most exchanges let you bind a key to specific IP addresses. A leaked secret then fails when used from the attacker's machine. This works well for a bot on a server with a fixed address. It works poorly for a laptop on changing networks, so use it where it fits.
Handle the secret like a password
- Show the secret only once, at creation, and store it in a password manager or secrets store.
- Do not paste secrets into chat messages, support tickets, screenshots or public repositories. Bots scan public code hosting sites for exposed keys within minutes.
- Load secrets from an environment variable, not from source code.
- Give each program its own key, named after it. When one leaks, you revoke one key and nothing else breaks.
- Never give a key to a site that asks for it in exchange for "free signals" or "copy trading" if you cannot verify the operator. Giving a stranger a trade key puts your funds under their control.
The following Python example shows the general pattern: the secret comes from the environment, and the program signs the request with HMAC-SHA256 so the secret itself is never sent. The exact signing format differs by exchange, so follow your exchange's documentation. This sketch only builds the signed query string and sends nothing.
import hashlib
import hmac
import os
import time
from urllib.parse import urlencode
def sign_query(secret, params):
query = urlencode(params)
signature = hmac.new(secret.encode(), query.encode(), hashlib.sha256).hexdigest()
return query + "&signature=" + signature
if __name__ == "__main__":
secret = os.environ.get("EXCHANGE_API_SECRET", "demo-secret-not-real")
params = {
"symbol": "BTCUSDT",
"timestamp": int(time.time() * 1000),
"recvWindow": 5000,
}
print(sign_query(secret, params))The timestamp and receive window limit replay: the exchange rejects a signed request that is too old. They do not help if the attacker holds the secret and can sign fresh requests, which is why least privilege and IP binding matter.
Rotation and cleanup
Review the API key list on a schedule, such as monthly. Delete every key for a program you no longer use. If a key appeared anywhere it should not have, treat it as compromised: revoke it first, then check recent activity, then create a new one.
Responding to a suspected session or key leak
Order matters. A reasonable sequence:
- Move to a clean device.
- Revoke all sessions and sign out everywhere.
- Delete all API keys.
- Change the password and re-check that your passkey and authenticator entries are the ones you registered.
- Review withdrawal allowlists and recent withdrawals, and contact the exchange through its official app or site if anything looks wrong.
- Check your email account's forwarding rules and login history, since the exchange relies on that inbox for alerts and resets.
Exercise
An attacker has copied your exchange session cookie with an infostealer, but you registered a passkey and use no SMS. Name two controls that still limit the damage, and explain why the passkey alone did not prevent the theft.
Show answer
Useful controls are re-authentication with a fresh passkey or code before withdrawals, a withdrawal address allowlist with a delay for new addresses, short session expiry, and remote logout after you notice the new-device alert. The passkey did not prevent the theft because it protects the login step by refusing to sign for the wrong origin. The malware stole the session token after a legitimate login, and the token works without any factor until it expires or is revoked.
Exercise
You run a portfolio tracker and a trading bot. How many API keys should you create, and what permissions should each have?
Show answer
Create two keys, one per program. The tracker gets read-only permission. The bot gets trading permission only, with withdrawals disabled, and an IP allowlist if it runs from a fixed address. Separate keys mean you can revoke one without breaking the other, and a leaked tracker key cannot place trades.