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
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);
Explanation
Build the API URL from config.
Create HttpWebRequest
with POST method.
Add JSON body to request stream.
Log the request for debugging.
Handling the Response
using (HttpWebResponse httpResponse = (HttpWebResponse)lhttpRequest.GetResponse())
{
using (Stream strm = httpResponse.GetResponseStream())
{
loutpout_Response = (new StreamReader(strm)).ReadToEnd();
var jsonobj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(loutpout_Response);
string reason = "", Token = "";
string status = jsonobj["status"].ToString();
string CurTime = jsonobj["currentTime"].ToString();
if (loutpout_Response.Contains("token")) Token = jsonobj["token"].ToString();
if (loutpout_Response.Contains("reason")) reason = jsonobj["reason"].ToString();
ExceptionLogging.SendErrorToText(" Token Response:" + loutpout_Response);
Explanation
Read the JSON response.
Extract status, token, reason.
Log the response for debugging.
Update Database with New Token
if (status == "success")
{
string qry = "select * from password (nolock) ";
DataSet ds = SqlHelper.ExecuteDataset(ConfigurationManager.ConnectionStrings["Databasename"].ToString(), CommandType.Text, qry);
string updateqry = "";
if (ds != null & ds.Tables[0].Rows.Count > 0)
{
updateqry = "update password set token='" + Token + "',tokenupdatetime=getdate() where active='1' ";
}
else
{
updateqry = "insert into password (token,tokenupdatetime,active,Pwd,updatedate) values('" + Token + "',getdate(),'1','','')";
}
SqlHelper.ExecuteNonQuery(ConfigurationManager.ConnectionStrings["Databasename"].ToString(), CommandType.Text, updateqry);
return Token;
}
else
{
NSE_ExceptionLogging.NSE_SendErrorToText(" Token status Error:" + reason);
return "login failed - " + reason;
}
Explanation
If status = "success"
β save new token in DB.
If table already has row β update.
Else β insert new row.
If failure β log error and return "login failed"
.
Exception Handling
catch (Exception ex)
{
string str = "Request:- " + pRequestJson + " \n Response:-" + loutpout_Response.ToString();
ExceptionLogging.SendErrorToText("Token Error:" + ex.Message.ToString());
return "error - " + ex.Message.ToString();
}
Explanation
Catches exceptions like network failure, invalid JSON.
Logs detailed info (request + response).
Returns "error - <message>"
to calling function.
4οΈβ£ loginrequest Class
public class loginrequest
{
public string member { get; set; }
public string loginId { get; set; }
public string password { get; set; }
}
Explanation
5οΈβ£ Web.config Settings
<add key="member" value="M00012"/>
<add key="loginid" value="XYZRCT"/>
<add key="password " value="ABC@1233"/>
<add key="LIVE " value="https://ssd-ase.ssvxxcs.com/"/>
Credentials are kept in web.config, not hardcoded.
6οΈβ£ Sample Request & Response
Request
{
"member": "M00012",
"loginId": "XYZRCT",
"password": "Zcs@44556677"
}
Success Response
{
"member": "M0002",
"loginId": "XYZRCT",
"status": "success",
"currentTime": "01-12-2025 14:30:45",
"token": "ssadfX3ddf4SZd"
}
Conclusion
Always check DB for existing token before generating a new one.
Reuse token if valid (age < 60 min), otherwise call API.
Store and update token in DB for future use.
Log both request and response for debugging.
Handle "error"
and "login failed"
gracefully to prevent system crashes.