Skip to main content
Question

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

  • May 31, 2022
  • 1 reply
  • 0 views

Forum|alt.badge.img+3

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

Forum|alt.badge.img+3
  • Author
  • New Contributor
  • 9 replies
  • May 31, 2022

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;
}


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings