HttpWebResponse displays siteminder login even though URLs are configured to be by passed in Siteminder - httpwebrequest

I am stumped on this problem and have come humbled to the experts on advice for my problem.
I have an ASP.NET MVC app that is Siteminder enabled. In addition, this app has a section of URLS that are web services which provide data to another application. Those URLS have been configured for "bypass" Siteminder authentication in the Siteminder setup. I've double checked the bypass to make sure the Siteminder configuration is correct. I can enter those URLs in a browser and the JSON data is displayed "without" Siteminder authentication. However....
The problem is when I use HttpWebResponse, Stream and StreamReader to retrieve the JSON data when siteminder is enabled, I get the Siteminder "login page HTML" as the string when StreamReader.ReadToEnd() is evoked instead of the JSON formatted data???
This is baffling because I another developer here can access the same web service and get the "correct" JSON formatted data in a PYTHON app. Also, I put it in a regular ASP.NET app so it's not an MVC issue. I get the same result.
Is there another class or library I should use? Is there a configuration setting I need to pass to the web service call? Any help would be greatly appreciated.
Here is the code of one of the web service calls.
public static string GetData()
{
string host = (string)System.Configuration.ConfigurationManager.AppSettings["WEBSERVICE_GET"];
string URL = host + "Api/GetData";
var end = string.Empty;
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
}
responseStream.Close();
response.Close();
}
}
catch (Exception ex)
{
EmailNotification.SendErrorEmail("Could not get Data from WEBSERVICE + ex);
}
return end;
}

Related

How to download Blazor server page html result

Under Asp.Net MVC I used to build the body of my mailing messages on a MVC view which the system downloaded through System.Net.HttpWebRequest.
Now that I am migrating to Blazor server, I can browse the page but if I try to download it to fill the body of the message I always get next body:
Loading... An unhandled exception has occurred. See browser dev
tools for details. Reload X
I tried both through a Blazor page and through a Cshtml razor page. My browser can see both successfully but I always get the same exception.
This is the code I use to download the page:
HttpResponseMessage response = await http.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var contentType = response.Content?.Headers?.ContentType?.MediaType;
if (contentType == "application/json" | contentType == "text/html")
{
string responseText = await response.Content?.ReadAsStringAsync() ?? "";
if (typeof(T) == typeof(string))
retval.Value = (T)(object)responseText;
else
retval.Value = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseText);
}
else
{
byte[] result = await response.Content.ReadAsByteArrayAsync();
retval.Value = (T)Convert.ChangeType(result, typeof(T));
}
}
}
I finally discovered the problem was on Program.cs from my .Net7 Server side Blazor app.
I was registering HttpClient as follows:
var http = new HttpClient();
builder.Services.AddScoped(sp => http);
This was Ok to access API data, but for some reason if you try to download a Html page source it throws a System.ObjectDisposedException: Cannot access a disposed object.
The right way to register the service to avoid this exception is:
builder.Services.AddHttpClient();
The problem is I no longer have a http variable in Program.cs, which I used to preload data from Api before the index page was ready.
Need a bit more detail:
What line threw the exception?
What was the exception?
What was value of string responseText or byte[] result?
I suspect either the DeserializeObject or Convert.ChangeType call failed. You should debug this; the answer will probably become apparent as you step through the code.

JIRA - pass credentials for a webrequest to API?

Trying to build a service that will grab info on a JIRA ticket based on an ID passed to it.
I'm calling the API to take the ID passed to the service, tack it onto the URL for the API and get the JSON object.
Problem is, it appears one must be logged on or registered on JIRA in order to use the API.
So if I use the code below to make my request, I get a 404 error, as I do on any browser which I've not used to log onto Jira
public string Get(string id)
{
string html = string.Empty;
string url = #"https://company.atlassian.net/rest/api/latest/issue/" + id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
return html;
}
I can add credentials to the request like so
request.Credentials = new NetworkCredential("vinnie#company.com","mypassword");
but I've no idea exactly what needs sending. I've tried the email address with which I'm set up in Jira but that doesn't work.
I have a suspicion that Jira adds a cookie to my browser which it uses to validate after the initial config - is that so? If so, what can I add/include on my web request to get it to run?
Am I just wildly off on the right way to access it? Or are there changes that can be made to the Jira side to allow requests?
You have to encode your credentials in Base64 format first and then these credentials can be put into your request as shown below:
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + base64Credentials);
Hope you're able to solve your problem by this approach!

Call authorized Web API using WebClient

After hours of searching the internet I decided to ask you guys for a little help.
I've written an Web API with couple of simple get/post methods. I'm using Individual user accounts authentication method.
Using the HttpClient I've managed to successfully call every AUTHORIZED get and post method as well as the /token endpoint used for generating authorization token.
The problem is that I must call these methods inside .NET Framework 3.5 project. So I've tried using WebClient to do this because I read that the HttpClient is not supported in .NET Framework 3.5.
GetAPIToken() METHOD generates Bearer token and it works.
private static string GetAPIToken(string userName, string password, string apiBaseUri)
{
using (WebClient client = new WebClient())
{
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var response = client.UploadString(apiBaseUri + "/Token", "POST", "grant_type=password&username=" + userName + "&password=" + password);
var jObject = JObject.Parse(response);
return jObject.GetValue("access_token").ToString();
}
}
This GET method works when I remove [Authorize] attribute from the Web API but I can't make it work when authorized.
//GET ODRAĐENI POSTUPCI
private static string GetOdradjeniPostupci(int Id, string token)
{
string apiBaseUri = "http://localhost:60511/";
string serviceUrl = apiBaseUri + "api/ZOdradjeniPostupci";
using (WebClient client = new WebClient())
{
client.Headers.Clear();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", "Bearer " + token);
var response = client.DownloadString(serviceUrl + "/GetZOdradjeniPostupci?cZdrUst=" + Id.ToString());
return response;
}
}
I get error 401 unathorized no matter what I try. (Different combinations from the internet regarding Authorization header).
Hope you could give me any advice on how to solve this.
I would appreciate it a lot.
Thanks.

Sharepoint 2013 REST api from desktop application - Authentication

I am trying to consume SharePoint 2013 REST services from a Desktop application ( cross-platform, cross-os ). Application is basically a HTML page in application view.
Is there a simple way I can authenticate my calls using HTTP methods ?
Yes, you can get authenticated and receive a digest via a REST call.
string url = "http://Your.SP.Site";
HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });
client.BaseAddress = new System.Uri(url);
string cmd = "_api/contextinfo";
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
client.DefaultRequestHeaders.Add("ContentType", "application/json");
client.DefaultRequestHeaders.Add("ContentLength", "0");
StringContent httpContent = new StringContent("");
var response = client.PostAsync(cmd, httpContent).Result;
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
JsonObject val = JsonValue.Parse(content).GetObject();
JsonObject d = val.GetNamedObject("d");
JsonObject wi = d.GetNamedObject("GetContextWebInformation");
retVal = wi.GetNamedString("FormDigestValue");
}
The above example shows how to retrieve the digest in C# with the HttpClient. This string needs to be passed as a header to all of the other rest calls you make to carry forward the authentication. You can create a credential by passing in a username and password if needed.
I have more examples here:
https://arcandotnet.wordpress.com/2015/04/01/sharepoint-2013-rest-services-using-c-and-the-httpclient-for-windows-store-apps/
You can do these calls in JavaScript as well and Microsoft has a lot of documentation on that. There is also .NET library, Microsoft.SharePoint.Client.DLL (CSOM) that simplifies this type of coding but you must have the library installed on the client.

Unable to consume OpenShift REST API in C#.net

I want to know how can I consume OpenShift Rest API into C#.net based application. I have gone through URL
https://access.redhat.com/documentation/en-US/OpenShift_Online/2.0/pdf/REST_API_Guide/OpenShift_Online-2.0-REST_API_Guide-en-US.pdf, in this there mentioned example for Ruby, Python and cRUL. but not mentioned for .Net. so I have created sample application for consuming this api.
below is the code -
string URL = "https://openshift.redhat.com/broker/rest/api";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml;";
try
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
}
While executing above code I am getting following error -
"The remote server returned an error: (406) Not Acceptable."
Please let me where I am doing wrong.
Thanks in advance
Jyoti
You are using the wrong HTTP header. ContentType is used for POST/PUT operations to tell server what to expect. When you GET a resource you must specify an Accept header.
request.Accept = "application/xml";