SecurityIntermediate

Authentication

Authentication is how a broker API verifies that a request genuinely comes from you and is authorised to act on your account, typically through API keys, short-lived access tokens, an OAuth-style login flow and often a TOTP second factor.

Quick answer: Authentication is how a broker API verifies that a request genuinely comes from you and is authorised to act on your account, typically through API keys, short-lived access tokens, an OAuth-style login flow and often a TOTP second factor.

In simple words

Authentication is the API's way of checking you are who you claim to be before it lets your code touch real money. Instead of a username typed into a screen, your program presents credentials — a key and a token — with every request. Because these credentials can place orders, protecting them is as important as protecting your bank password.

Purpose

Authentication exists so that only you can drive your account through the API; without it, anyone who guessed your endpoint could trade on your behalf, so it is the security foundation of everything else.

Professional explanation

API keys: identifying the application

An API key (often a key plus a secret) identifies your application to the broker. The public key names you; the secret proves it is really you and must never be exposed. Keys are relatively long-lived and are usually issued once when you register an app. Because a leaked secret lets an attacker impersonate your application, it is treated like a password: never committed to source code, never logged, never sent to the browser. The key identifies; it does not, by itself, grant a live trading session — that usually requires a further login step producing a short-lived token.

Access tokens and sessions

Most broker APIs separate long-lived identity (the API key) from a short-lived access token that authorises the current trading session. You obtain the token by completing a login flow, and then attach it to every request, commonly in an Authorization header. Access tokens typically expire — often daily, aligned with the trading day — which limits the damage if one leaks and forces a fresh, deliberate login. Some systems also issue a refresh token that can mint new access tokens without a full re-login. Your client must detect an expired token (a 401) and re-authenticate cleanly rather than looping on failed requests.

OAuth-style login flows

Rather than handing your broker password to a third-party app, modern broker APIs use an OAuth-style redirect flow. Your app sends the user to the broker's own login page; the user authenticates there (password plus second factor); the broker redirects back with a short-lived request token; and your app exchanges that request token, together with the API secret, for an access token. The point of this dance is that the password is entered only on the broker's domain and never touches the app, and the resulting token is scoped and expirable. Understanding the exact sequence — request token, exchange, access token — is essential because each broker's endpoints and field names differ.

TOTP and the second factor

Two-factor authentication adds a time-based one-time password (TOTP) — the rotating six-digit code from an authenticator app — on top of the password. TOTP is derived from a shared secret seed and the current time using a standard algorithm, so the same seed generates the same code on your device and the broker's server without any network call. For automated login, some systems generate the TOTP programmatically from the seed. This is powerful but dangerous: the TOTP seed is itself a high-value secret, and storing it insecurely defeats the entire purpose of the second factor. If you automate TOTP, the seed deserves the same protection as the API secret.

Storing secrets safely — never hardcode

The single most important rule is that secrets never live in source code. Hardcoding an API secret or token into a Python file means it travels into version control, and a public or later-shared repository leaks it permanently — attackers actively scan public code for exactly these strings. Instead, secrets belong in environment variables, a dedicated secrets manager, an encrypted vault, or a config file that is excluded from version control (via a gitignore entry) and readable only by the running user. On shared or cloud machines, prefer a managed secrets service over plaintext files. Rotating keys periodically and immediately on any suspected exposure is standard hygiene.

Least privilege, scope and revocation

Good authentication design also limits what a credential can do and for how long. Where a broker offers scoped keys or read-only tokens, use the narrowest scope a component needs — a monitoring dashboard should not hold order-placement rights. Keep the ability to revoke a key instantly, and know the procedure before you need it, because the response to a suspected leak is to revoke first and investigate second. Combine short token lifetimes, least privilege and fast revocation and a leaked credential becomes a contained incident rather than a drained account.

API key vs access token

AspectAPI key/secretAccess token
PurposeIdentifies your applicationAuthorises the current session
LifetimeLong-livedShort-lived (often daily)
Obtained viaApp registrationLogin flow / exchange
If leakedRevoke and reissue the keyExpires soon, but revoke session
Sent howUsed to sign / exchangeAttached to each request header

Practical example

Illustrative example (Indian market)

You register an app and receive an API key and secret, which you store as environment variables on your server, never in code. Each morning your program runs the login flow: it obtains a request token via the broker's login page (supplying username, password and a TOTP generated from a securely stored seed), then exchanges that request token plus the secret for a daily access token. It attaches that token to every REST and WebSocket call. When a mid-session request returns 401, the client re-runs the login rather than retrying blindly. None of these credentials ever appear in logs or the repository.

Indian broker APIs typically expire the access token at end of day, so a live system must re-authenticate before each session — and because most now enforce TOTP-based 2FA, unattended login requires securely storing the TOTP seed. Treat that seed as equivalent to your trading password: in a secrets manager, never in a code file that could reach a repository.

Advantages

  • Ensures only authorised code can read your account and place orders
  • Short-lived tokens limit the blast radius if a credential leaks
  • OAuth-style flows keep your broker password on the broker's domain, never in the app
  • Scoped and revocable credentials let you grant least privilege and shut off access fast

Limitations

  • Automating TOTP means storing the seed, a high-value secret that can undermine 2FA if exposed
  • Daily token expiry forces a re-authentication routine that itself must be reliable
  • A single leaked secret can drain or disrupt the account before you notice
  • Login flows and field names differ per broker and change between API versions
  • Managing secrets correctly across dev, test and production adds real operational overhead

Common mistakes

  • Hardcoding API keys, secrets or tokens into source code that reaches version control
  • Logging tokens or secrets, or printing them to the console during debugging
  • Storing the TOTP seed in plaintext alongside the code, defeating two-factor security
  • Retrying requests on a 401 instead of re-authenticating to obtain a fresh token
  • Committing a config file with real credentials because it was not added to gitignore
  • Granting a monitoring or research component full order-placement privileges it does not need

Professional usage

Professional setups inject secrets at runtime from a managed vault or environment, never from the codebase, and enforce that no credential is ever logged. They separate identity (long-lived key) from session (short-lived token), automate a clean re-authentication path on 401, and apply least privilege so each component holds only the scope it needs. Key rotation is scheduled, revocation procedures are rehearsed, and any suspected leak triggers an immediate revoke-first response.

Key takeaways

  • Authentication proves a request is really you and is allowed to act on the account
  • Separate long-lived API keys (identity) from short-lived access tokens (session)
  • OAuth-style flows and TOTP keep the password on the broker and add a second factor — but the seed is a secret too
  • Never hardcode secrets; use env vars or a secrets manager, apply least privilege, and be ready to revoke

Frequently asked questions

What is authentication in a trading API?
It is the mechanism by which the broker verifies a request genuinely comes from you and is authorised to act on your account. It typically combines an API key that identifies your app with a short-lived access token obtained through a login flow.
What is the difference between an API key and an access token?
The API key (with its secret) is a long-lived credential that identifies your application. The access token is short-lived and authorises the current trading session; you obtain it through a login flow and attach it to each request. Tokens usually expire daily.
Why should I never hardcode API keys?
Because hardcoded secrets travel into version control and can leak permanently if the repository is ever public or shared. Attackers actively scan public code for keys. Store secrets in environment variables or a secrets manager instead, excluded from version control.
What is an OAuth-style login flow?
It is a redirect sequence where the user logs in on the broker's own page, the broker returns a short-lived request token, and your app exchanges that plus its secret for an access token. The password never touches your app, only the broker's domain.
What is TOTP and why is it used?
TOTP is a time-based one-time password — the rotating six-digit code from an authenticator app, derived from a shared seed and the current time. It adds a second factor so that a stolen password alone cannot log in and trade.
Is it safe to automate TOTP login?
It can be, but only if the TOTP seed is stored as securely as your password — in a secrets manager, never in plaintext beside the code. Storing the seed carelessly defeats the entire point of two-factor authentication.
Where should I store my API secrets?
In environment variables, an encrypted vault, or a managed secrets service — never in source code or logs. On shared or cloud machines, prefer a managed secrets manager over plaintext config files, and restrict file permissions to the running user.
How often do access tokens expire?
It varies by broker, but many Indian broker tokens expire at end of trading day, requiring a fresh login each morning. Design a reliable re-authentication routine and detect expiry (a 401) to trigger it cleanly.
What should I do if a request returns 401?
A 401 means authentication failed or the token expired. Re-run the login flow to obtain a fresh token rather than retrying the same request, which will keep failing. Do not confuse this with a 429 rate-limit, which needs backoff instead.
What is least privilege in API auth?
It means giving each component only the access it needs — for example, a monitoring dashboard gets read-only scope, not order-placement rights. Narrow scope limits the damage if any single credential is compromised.
What do I do if I think a key has leaked?
Revoke it immediately, then investigate. Fast revocation turns a leak into a contained incident. Afterwards, reissue a new key, rotate related secrets, and review how the exposure happened to prevent a repeat.
Can two-factor authentication be skipped for automation?
You should not skip it; most brokers now enforce it. Instead, automate it securely by storing the TOTP seed in a secrets manager and generating codes at login time. Disabling 2FA to simplify automation trades away a core protection.
Is authentication the same as authorisation?
No. Authentication proves who you are; authorisation determines what you are allowed to do. A valid token authenticates you, but scope and permissions decide whether it may place an order or only read data.

Voice search & related questions

Natural-language questions people ask about Authentication.

What is authentication for a trading API?
It is how the broker checks your code really is you before letting it trade. Your program presents a key and a token with every request, like a password for a program.
Why should I never put my API key in my code?
Because code often ends up in version control, and a leaked key lets someone else trade your account. Keep secrets in environment variables or a vault, never in the source.
What is TOTP in simple words?
It is the rotating six-digit code from an authenticator app. It proves you have your device, adding a second lock on top of your password.
Where should I keep my trading API secrets?
In a secrets manager or environment variables that are not in your code or logs. On a server, a managed vault beats a plaintext file.
What do I do if my token expires mid-session?
Re-run the login to get a fresh token instead of retrying the failed request. An expired token shows up as a 401 error.
What if my API key leaks?
Revoke it right away, then reissue a new one and rotate related secrets. Revoking first turns a scary leak into a contained problem.

Sources & references

    Last reviewed 11 July 2026. Educational content only — not investment advice. Markets and rules change; verify current conventions with SEBI, NSE/BSE and your broker.

    Educational content only — not investment advice. Examples use illustrative numbers and simplified models. Algorithmic trading and derivatives involve substantial risk. See our Risk Disclosure and SEBI Disclaimer.