On this page

Tokens expire. Handling that deliberately is the difference between a script that works while you watch it and one that runs unattended.

Valid until about 4:00 AM IST

An access token stays valid until the daily server restart (start of day) at about 4:00 AM IST. Logging in again issues a new token and the old one stops working. To renew, run the OAuth login again.

What you get back at login

FieldWhat it isNotes
access_tokenThe credential for every other call64 hexadecimal characters, no dashes. Send as Bearer.
expires_inWhen it expiresa Unix timestamp, not a duration
refresh_tokenA refresh credentialno endpoint accepts it See below.
lastaccesstimePrevious access timeA Unix timestamp.
uid, actidYour user and account IDStore these - almost every request needs them.
The relevant part of a GenAcsTok response
{
"stat": "Ok",
"access_token": "dde92200b0744defa1d98e3b3cc0027530c6b31627619dd318c9e3cd88ecd33a",
"expires_in": "1756990407",
"refresh_token": "5e48d5f406a695014e934f601d0fe2bc9deb4b5800368d5927084d865660e2d9"
}
expires_in is a timestamp, not a duration

The name suggests "seconds from now", which is the usual OAuth meaning. The documented value 1756990407 is a Unix timestamp - an absolute moment, not a span.

Treating it as a duration would have you believe the token lasts about 55 years. Compare it against the current time instead.

Reading expires_in correctly
import time
from datetime import datetime, timezone, timedelta

IST = timezone(timedelta(hours=5, minutes=30))


def token_expiry(login_response):
  """Returns the token's expiry as an aware datetime, or None."""
  raw = login_response.get("expires_in")
  if not raw:
      return None
  # An absolute Unix timestamp, despite the name.
  return datetime.fromtimestamp(int(raw), tz=timezone.utc)


def seconds_remaining(login_response):
  expiry = token_expiry(login_response)
  return (expiry.timestamp() - time.time()) if expiry else None


# expires_in "1756990407" -> 2025-09-04 11:33:27 UTC, i.e. 17:03 IST.
# The documented sample's own expiry is in the past; it is an illustration,
# not a live value.

What invalidates a token early

CauseEffectHow you find out
expires_in is reachedThe token stops working401, or Session Expired
You call LogoutImmediate invalidationSubsequent calls fail
The user logs in elsewhereThe documentation describes a login superseding a sessionSession Expired : Invalid Session Key
Your IP address changesThe token is still valid but unusable from herean empty 401 — indistinguishable from a bad token

How expiry shows up

In two different ways, at the two different error layers. Handle both.

Request
Empty body
HTTP/1.1 403 Forbidden
Content-Length: 0
Response
HTTP 200, with a message
{
"stat": "Not_Ok",
"emsg": "Session Expired : Invalid Session Key"
}
A 401 is ambiguous, and the ambiguity matters

An empty 401 means either the token is bad or this machine's IP is not registered. The response cannot tell you which.

So re-authenticating in response to a 401 is right only half the time. If a fresh token also gets a 401, stop retrying and check the IP - otherwise you will loop, minting tokens that cannot work.

About refresh_token

Documentation information not available

The GenAcsTok response includes a refresh_token, and the field appears in the documented response table. But no endpoint is documented that accepts it: there is no refresh call anywhere in the Infinn documentation.

So do not design around silent renewal. Store the value in case a refresh endpoint is published, and in the meantime treat re-running the full login flow as the only way to obtain a new token.

What this means in practice

Renewal needs a human: someone has to open a browser and sign in, because that is what produces a login code.

So an unattended system cannot refresh itself indefinitely. The usual pattern is a scheduled login before the market opens, with the token stored where the rest of the system can read it. Plan for one manual step per session.

A session manager

Store, validate and fail clearly
"""Manage an Infinn access token across process restarts.

Because no refresh endpoint is documented, this cannot renew silently. What
it can do is refuse to make doomed calls, persist a token so a restart does
not need a new login, and distinguish the two causes of a 401 so the
operator is told the right thing.
"""
import json
import os
import time
from pathlib import Path

TOKEN_FILE = Path(os.environ.get("INFINN_TOKEN_FILE", "~/.infinn-token.json")).expanduser()
# Treat a token as expired slightly early, so a long-running call does not
# start on a valid token and finish on an invalid one.
SAFETY_MARGIN = 120


class SessionExpired(RuntimeError):
  """Raised when a new login is required. Not retryable."""


class Session:
  def __init__(self, token=None, expires_at=None, uid=None):
      self.token = token
      self.expires_at = expires_at
      self.uid = uid

  # --- persistence --------------------------------------------------------

  @classmethod
  def load(cls):
      """Reads a stored session, or returns an empty one."""
      try:
          data = json.loads(TOKEN_FILE.read_text())
      except (OSError, ValueError):
          return cls()
      return cls(data.get("access_token"),
                 data.get("expires_at"),
                 data.get("uid"))

  def save(self):
      TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True)
      TOKEN_FILE.write_text(json.dumps({
          "access_token": self.token,
          "expires_at": self.expires_at,
          "uid": self.uid,
      }))
      # The token is a credential. Keep it to the owner where the OS
      # supports it; on Windows this is a no-op and ACLs apply instead.
      try:
          TOKEN_FILE.chmod(0o600)
      except (OSError, NotImplementedError):
          pass

  @classmethod
  def from_login(cls, login_response, uid):
      expires = login_response.get("expires_in")
      session = cls(
          token=login_response["access_token"],
          expires_at=int(expires) if expires else None,
          uid=uid,
      )
      session.save()
      return session

  # --- use ----------------------------------------------------------------

  @property
  def valid(self):
      if not self.token:
          return False
      if self.expires_at is None:
          # No expiry recorded. Optimistic, but a 401 will correct us.
          return True
      return time.time() < self.expires_at - SAFETY_MARGIN

  def require(self):
      """Returns the token, or raises before wasting a call."""
      if not self.valid:
          raise SessionExpired(
              "No valid access token. Run the login flow:\n"
              "https://api.infinn.in/OAuthlogin/investor-entry-level/login"
              "?api_key=<API_KEY>&route_to=<sha256(USER_ID|SECRET)>"
          )
      return self.token

  def invalidate(self):
      self.token = None
      self.expires_at = None
      try:
          TOKEN_FILE.unlink()
      except OSError:
          pass


def call_with_session(session, path, payload):
  """Makes a call, converting auth failures into a clear instruction."""
  token = session.require()
  try:
      return call(path, payload, token)
  except InfinnError as err:
      # Layer 1: a 401 is ambiguous -- bad token, or unregistered IP.
      if err.status == 401:
          session.invalidate()
          raise SessionExpired(
              "HTTP 401. Either the token is no longer valid, or this "
              "machine's public IP is not the one registered on your "
              "Infinn profile. Check the IP first -- a new token will not "
              "help if the address is wrong."
          ) from err

      # Layer 2: this one is unambiguous.
      if err.status == 200 and "session expired" in str(err).lower():
          session.invalidate()
          raise SessionExpired("Session expired. Log in again.") from err

      raise

Logging out on purpose

Logout invalidates the token immediately. Call it when a user signs out, and when you suspect a token has leaked - it is faster than waiting for expiry and does not require changing any keys.

Invalidate a token now
curl --request POST \
--url 'https://api.infinn.in/NorenWClientAPI/Logout' \
--header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
--header 'Content-Type: text/plain' \
--data 'jData={"uid":"IN001"}'

Storing a token safely

WhereVerdictWhy
An environment variablegoodNot in source control, not in a file, easy to rotate.
A secrets managerbestAuditable and rotatable. Worth it for anything production.
A file with owner-only permissionsacceptableFine for a local tool. Keep it out of the repository.
A source filenoIt will reach version control eventually.
Browser localStoragelocal tools onlyReadable by anything running on that origin. Never on a page you ship to users.
A mobile app bundlenoExtractable by anyone who downloads the app.
A log filenoRedact the Authorization header explicitly - most logging middleware records it in full.
A token is as powerful as a password

Anyone holding it can place orders on the account until it expires. It should never appear in a repository, a client-side bundle, a URL, a screenshot or a log line.

If you log requests for debugging, redact the Authorization header explicitly - most logging middleware will happily record it in full.

Redact credentials before logging
SENSITIVE_HEADERS = {"authorization", "cookie"}
SENSITIVE_FIELDS = {"accesstoken", "access_token", "checksum",
                  "pwd", "secret_key"}


def safe_headers(headers):
  """Masks credential headers, keeping enough to identify which token."""
  out = {}
  for key, value in headers.items():
      if key.lower() in SENSITIVE_HEADERS:
          text = str(value)
          out[key] = (text[:14] + "…" + text[-4:]) if len(text) > 24 else "***"
      else:
          out[key] = value
  return out


def safe_payload(payload):
  """Masks credential fields inside a jData object."""
  return {
      k: ("***" if k.lower() in SENSITIVE_FIELDS else v)
      for k, v in payload.items()
  }

The WebSocket uses the same token

The connect message carries accesstoken, and the same expiry applies. For what happens to an open connection at expiry, see Known limitations. A reconnect after expiry fails with {"t":"ak","s":"NOT_OK"} and a close code of 1008.

Validate before reconnecting

In a reconnect loop, check the token with a cheap REST call such as User Details before retrying the socket. It turns an opaque stream failure into a clear message, and it stops a loop that can never succeed.

Next

Esc
↑↓ navigate↵ openEsc close/ to search