When working with NSE IPO APIs or any secure third-party API, you must handle authentication tokens. Tokens are required for every subsequent request, but they also expire after a certain period (e.g., 60 minutes).
In this blog, let’s break down a real-world C# implementation for:
Checking if a valid token exists in the database
Generate a new token when expires
Updating the database with the latest token
Handling API request/response safely
1️⃣ Token Validation Usage
token = reqtoken.validtoken();
if (token.Contains("error") || token.Contains("login failed"))
{
script = "alertify.alert('Please contact administrator')";
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alertifyScript", script, true);
}
else
{
string status = jsonmainobj.status;
string nsereason = jsonmainobj.reason;
if (status == "success")
{
// continue process...
}
}
Explanation
reqtoken.validtoken()→ calls our function to get a valid token.If token contains
"error"or"login failed"→ process ends and error is logged.Else → proceed with business logic only if status is
"success".
2️⃣ The validtoken() Function
public string validtoken()
{
string checksql = "select * from password (nolock) ";
DataSet ds = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["DatabaseName"].ToString(), CommandType.Text, checksql);
if (ds.Tables[0] != null & ds.Tables[0].Rows.Count > 0)
{
TimeSpan ts = Convert.ToDateTime(DateTime.Now.ToString("hh:mm tt"))
- Convert.ToDateTime(ds.Tables[0].Rows[0]["tokenupdatetime"].ToString());
if (Math.Abs(ts.TotalMinutes) < 60)
{
return ds.Tables[0].Rows[0]["token"].ToString();
}
else
{
return GenerateToken();
}
}
else
{
return GenerateToken();
}
}
Line by Line
Query DB table NSE_ipopasswordmaster.
If record exists:
Calculate time difference between current time and last token update time.
If token age < 60 minutes → return existing token.
Else → call
GenerateToken()to create a new one.
If no record exists → generate a new token.
This prevents unnecessary token requests and reuses valid tokens.
3️⃣ The GenerateToken() Function
public string GenerateToken()
{
string pRequestJson = "";
loginrequest req = new loginrequest();
NSEIPO nseipo = new NSEIPO();
req.member = ConfigurationManager.AppSettings["member"].ToString();
req.loginId = ConfigurationManager.AppSettings["loginid"].ToString();
req.password = ConfigurationManager.AppSettings["password"].ToString();
string reqjson = (new JavaScriptSerializer()).Serialize(req);
pRequestJson = reqjson;
Explanation
Create login request object (
loginrequest).Fetch credentials from
web.config.Serialize request to JSON (required by API).
Preparing the HTTP Request
string lServiceUrl = ConfigurationManager.AppSettings[" LIVE"].ToString() + "/asde/U1/logintoken";//log
BusinessData.NSE_ExceptionLogging.NSE_SendErrorToText("Token Url:" + lServiceUrl);
string loutpout_Response = "";
HttpWebRequest lhttpRequest = null;
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate pCertificate, System.Security.Cryptography.X509Certificates.X509Chain pChain, System.Net.Security.SslPolicyErrors pSSLPolicyErrors) { return true; };
lhttpRequest = (HttpWebRequest)WebRequest.Create(new Uri(lServiceUrl));
lhttpRequest.Accept = "application/json";
lhttpRequest.ContentType = "application/json";
lhttpRequest.KeepAlive = true;
lhttpRequest.Method = "POST";
byte[] bytes1 = Encoding.UTF8.GetBytes(pRequestJson);
using (Stream stream = lhttpRequest.GetRequestStream())
{
stream.Write(bytes1, 0, bytes1.Length);
stream.Close();
}
ExceptionLogging.SendErrorToText("Token Request:" + pRequestJson);

Join the conversation! Your thoughts help the community grow.