Authentication overview

SmartAPI, provided by Angel One, employs a multi-factor authentication system to secure access to its trading and market data functionalities. This system is designed to ensure that only authorized applications and users can perform operations such as placing orders, managing portfolios, or retrieving real-time market data. The core of SmartAPI's authentication process involves generating a session token after validating a set of credentials, including an API key, a client ID, and a Time-based One-Time Password (TOTP) SmartAPI authentication documentation. Once a session token is obtained, it must be included in subsequent API requests to maintain an authenticated state.

This approach helps protect sensitive financial operations by requiring more than one form of verification. The use of an API key identifies the application, the client ID identifies the user's trading account, and the TOTP provides a dynamic, time-sensitive element for enhanced security. Developers integrate these credentials into their applications, typically during an initial login flow, to establish a secure connection with the SmartAPI platform.

Supported authentication methods

SmartAPI uses a specific combination of authentication factors rather than distinct methods like OAuth 2.0 or basic authentication in isolation. The primary mechanism for establishing an authenticated session involves:

  • API Key: A static credential that identifies your application to the SmartAPI platform. It is generated through the developer dashboard.
  • Client ID: Your unique identifier as an Angel One client, linking API access to your trading account.
  • Time-based One-Time Password (TOTP): A dynamic, ephemeral code generated by an authenticator application (e.g., Google Authenticator) that changes periodically. This adds a crucial layer of multi-factor authentication.

Upon successful submission of these credentials to the login endpoint, SmartAPI returns an access token and a refresh token. The access token is a bearer token that must be included in the Authorization header of subsequent API requests. The refresh token allows for obtaining new access tokens without re-authenticating with the API key, client ID, and TOTP, thus maintaining an active session for an extended period.

The following table outlines the components involved in SmartAPI's authentication:

Component Purpose Security Level
API Key Identifies the calling application Moderate (static credential)
Client ID Identifies the Angel One trading account Moderate (static credential)
TOTP Provides a dynamic, time-sensitive second factor High (dynamic, ephemeral)
Access Token Authorizes subsequent API requests for a session High (short-lived, bearer token)
Refresh Token Obtains new access tokens without full re-authentication High (longer-lived, used securely)

Getting your credentials

To begin using SmartAPI, you must first register as a developer and obtain the necessary credentials. The process typically involves these steps:

  1. Create an Angel One Trading Account: If you do not already have one, you will need to open a trading account with Angel One. SmartAPI access is free for Angel One clients SmartAPI official website.
  2. Register for SmartAPI: Navigate to the SmartAPI developer portal and register your application. During registration, you will provide details about your application and agree to the terms of service.
  3. Generate API Key: Once registered, you can generate an API key from your SmartAPI developer dashboard. This key is unique to your application and serves as its primary identifier.
  4. Note Your Client ID: Your Angel One client ID will be used as part of the authentication process. This is typically available in your Angel One account details.
  5. Set Up TOTP: Configure a Time-based One-Time Password (TOTP) authenticator application (such as Google Authenticator or Authy) with your Angel One account. This generates the dynamic codes required for login.

It is crucial to keep your API key and client ID confidential and stored securely. The TOTP is generated on a separate device, adding a layer of security by requiring physical access or control over that device during login.

Authenticated request example

After successfully authenticating and obtaining an access token, subsequent requests to SmartAPI endpoints require this token in the Authorization header. The token is typically prefixed with "Bearer ".

Here's a Python example demonstrating how to obtain an access token and then use it for a subsequent request, leveraging the official SmartAPI Python SDK SmartAPI SDK documentation:

from SmartApi import SmartConnect
import pyotp # For TOTP generation

# --- Step 1: Initialize SmartConnect and Authenticate ---

API_KEY = "YOUR_API_KEY" # Replace with your actual API Key
CLIENT_ID = "YOUR_CLIENT_ID" # Replace with your Angel One Client ID
TOTP_SECRET = "YOUR_TOTP_SECRET" # Replace with your TOTP secret key

# Initialize SmartConnect
obj = SmartConnect(api_key=API_KEY)

# Generate TOTP
totp = pyotp.TOTP(TOTP_SECRET).now()

# Perform login to get session tokens
data = obj.generateSession(CLIENT_ID, totp)

# Check for successful login and extract tokens
if data and data.get("status"):
    try:
        access_token = data["data"]["jwtToken"]
        refresh_token = data["data"]["refreshToken"]
        feed_token = data["data"]["feedToken"]
        print(f"Access Token: {access_token}")
        print(f"Refresh Token: {refresh_token}")
        print(f"Feed Token: {feed_token}")

        # Set the access token for subsequent requests in the SDK
        obj.setAccessToken(access_token)
        obj.setRefreshToken(refresh_token)
        obj.setFeedToken(feed_token)

        # --- Step 2: Make an authenticated request (e.g., get user profile) ---
        # Example: Get user profile information
        profile_data = obj.getProfile(data["data"]["jwtToken"])
        if profile_data and profile_data.get("status"):
            print("\nUser Profile Data:")
            print(profile_data["data"])
        else:
            print(f"Failed to get profile data: {profile_data.get('message', 'Unknown error')}")

    except KeyError as e:
        print(f"Error parsing login response: Missing key {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
else:
    print(f"Login failed: {data.get('message', 'Unknown error')}")

# --- Logout (optional) ---
# obj.terminateSession(CLIENT_ID)

This example first generates a session by providing the client ID and TOTP, then uses the obtained jwtToken (access token) to retrieve the user's profile. The SmartAPI SDK handles the underlying HTTP request and header management once the access token is set.

Security best practices

Adhering to security best practices is essential when integrating with financial APIs like SmartAPI to protect sensitive trading information and prevent unauthorized access:

  • Keep API Keys Confidential: Never hardcode API keys directly into client-side code, commit them to public repositories, or expose them in client-facing applications. Store API keys as environment variables or in secure configuration management systems.
  • Secure TOTP Secret: The TOTP secret key is critical for generating one-time passwords. Treat it with the same level of security as a password. Do not store it in plain text or in easily accessible locations.
  • Use Environment Variables: For development and deployment, use environment variables to inject API keys, client IDs, and TOTP secrets into your applications. This prevents them from being directly included in your codebase.
  • Encrypt Data in Transit: Always use HTTPS for all API communication. SmartAPI enforces HTTPS, ensuring that data exchanged between your application and the API is encrypted, protecting against eavesdropping and man-in-the-middle attacks. This is a fundamental principle for securing web communications Mozilla's HTTPS explanation.
  • Manage Access Tokens Securely: Access tokens are short-lived. Store them in memory for the duration of the session and avoid persisting them to disk unnecessarily. If persistence is required, ensure it's encrypted.
  • Implement Refresh Token Rotation: If SmartAPI supports refresh token rotation, implement it. This means that each time a refresh token is used to obtain a new access token, a new refresh token is also issued, and the old one is invalidated. This limits the window of opportunity for a compromised refresh token.
  • Log and Monitor API Usage: Implement logging for API calls, especially failed authentication attempts. Monitor these logs for unusual activity that might indicate an attempted breach.
  • Regularly Review Permissions: If your application interacts with different scopes or permissions, regularly review and ensure that your API key or associated account only has the minimum necessary permissions required for its functionality (principle of least privilege).
  • Handle Errors Gracefully: Implement robust error handling for API responses, particularly for authentication failures. Avoid exposing sensitive information in error messages to end-users.
  • Keep SDKs and Dependencies Updated: Regularly update the SmartAPI SDKs and any other third-party libraries used in your application to benefit from the latest security patches and improvements.