Token EndPoint (/api/v1/auth/token) Returning 401 Unauthorized error

SheikSena
New Contributor

Hello All,

I'm trying to generate the Bearer token using C# via /api/v1/auth/token API and I'm getting 401 Unauthorized error. But, when I call the same API and with the same credentials in POSTMAN I'm getting 200 with a token in the response. Can someone help me with how to generate tokens using C#?. Thanks.

 

Code:

string response = string.Empty;

try
{
Uri tokenUrl = new Uri(ConnectionProproperties.url);
WebRequest webRequest = HttpWebRequest.Create(tokenUrl);
HttpWebRequest httpWebRequest = (HttpWebRequest) webRequest;

NetworkCredential networkCredential = new NetworkCredential("xyzzzz", "xyzzzz");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(tokenUrl, "Basic", networkCredential);

httpWebRequest.Method = "POST";
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = credentialCache;

WebResponse webResponse = webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
response = streamReader.ReadToEnd();

responseStream.Close();
webResponse.Close();

return response;
}
catch (WebException ex)
{
if ((HttpWebResponse) ex.Response != null)
{
response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return response;
}

1 REPLY 1

SheikSena
New Contributor

Code:

string response = string.Empty;

try
{
Uri tokenUrl = new Uri(ConnectionProproperties.url);
WebRequest webRequest = HttpWebRequest.Create(tokenUrl);
HttpWebRequest httpWebRequest = (HttpWebRequest) webRequest;

NetworkCredential networkCredential = new NetworkCredential("xyzzzz", "xyzzzz");
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(tokenUrl, "Basic", networkCredential);

httpWebRequest.Method = "POST";
httpWebRequest.PreAuthenticate = true;
httpWebRequest.Credentials = credentialCache;

WebResponse webResponse = webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);
response = streamReader.ReadToEnd();

responseStream.Close();
webResponse.Close();

return response;
}
catch (WebException ex)
{
if ((HttpWebResponse) ex.Response != null)
{
response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
}
return response;
}