SSRS Reporting services Rest API Unauthorized - c#

I'm trying to get a list of reports from SSRS Rest API. I can see them when I navigate to the URL http://someaddress/reports/api/V2.0/reports in chrome
When I navigate there in the browser an input box shows up and asks for a username and password.
So I've tried this:
var client = new HttpClient(){BaseAddress= new Uri("Http://someaddress/reports/api/V2.0");
client.DefaultRequestHeaders.Add("Username",#"someuser");
client.DefaultRequestHeaders.Add("Password",#"some password");
var response= await _client.GetAsync("reports");
It's returning 401 unauthorized.
Can someone please explain how I can pass the username and password in so I get the correct response?

If you are using username and password, you need to use NTLM cretendials to authenticate the request. You can achieve it using HttpClientHandler and CredentialCache, like this:
var uri = new Uri("Http://someaddress/reports/api/V2.0");
var networkCredential = new NetworkCredential(#"someuser", #"some password", "");
var credentialsCache = new CredentialCache { { uri, "NTLM", networkCredential } };
var handler = new HttpClientHandler { Credentials = credentialsCache };
var client = new HttpClient(handler) { BaseAddress = uri };
var response= await client.GetAsync("reports");

Related

POST Request in xamarin forms

I'm trying authenticate a user on WordPress using a REST API Route configured with POST method. I have already done this with it configured with the GET method but this isn't exactly safe for user authentication. So I need to send a POST request to this endpoint with the email and password I get from the login form. The code I currently have does get to the endpoint which uses the function and returns a string if I put echo "It works". However if I try to echo or return the values of my POST it returns nothing.
Xamarin Code:
var password = Wachtwoord.Text;
var email = Email.Text;
var client = new HttpClient();
var content = new StringContent(
JsonConvert.SerializeObject(new { email = email, password = password }));
var result = await client.PostAsync("https://staging.myopinion.be/wp-json/app-endpoint/auth", content).ConfigureAwait(false);
if (result.IsSuccessStatusCode)
{
var tokenJson = await result.Content.ReadAsStringAsync();
var test = tokenJson;
}
WordPress Functions code:
function authenticate_user(WP_REST_Request $request) {
$login = $_POST;
$email = $_POST['email'];
$password = $login['password'];
echo $email;
}

Login to Scraping Testing Ground website and Scrape html after

I am building web scraper and I need to scrape html from website that needs login.
I tried most of stackoverflow anwsers I didn't find anwser I am looking for. I don't know how to get the result html.
var baseAddress = new Uri("http://testing-ground.scraping.pro/login");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
//usually i make a standard request without authentication, eg: to the home page.
//by doing this request you store some initial cookie values, that might be used in the subsequent login request and checked by the server
var homePageResult = client.GetAsync("/login");
homePageResult.Result.EnsureSuccessStatusCode();
var content = new FormUrlEncodedContent(new[]
{
//the name of the form values must be the name of <input /> tags of the login form, in this case the tag is <input type="text" name="username">
new KeyValuePair<string, string>("usr", "admin"),
new KeyValuePair<string, string>("pwd", "12345"),
});
var loginResult = client.PostAsync("/login", content).Result;
loginResult.EnsureSuccessStatusCode();
Console.WriteLine(loginResult);
I expect the loginResult to be successfull only if
usr is admin
and
pwd is 12345
but no matter what it is positive. Also my main goal is to scrape the result HTML so in this case it should scrape HTML that doesn't have login form, but instead welcome text.
All right, I got it! This is working code
public static async Task Login()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://testing-ground.scraping.pro/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var username = "admin";
var password = "12345";
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("usr", username),
new KeyValuePair<string, string>("pwd", password),
});
HttpResponseMessage responseMessage = await client.PostAsync("/login?mode=login", formContent);
var response = await responseMessage.Content.ReadAsStringAsync();
Console.WriteLine(response);
}
}
I realised that requestURL should be /login?mode=login insead of /login
I changed also DefaultRequestHeaders to application/x-www-form-urlencoded after inspecting in fiddler the headers.

Is it possible to use an HTTPClient with Windows authentication within an AWS Lambda function?

Is it possible to specify Windows credentials to HttpClient within an AWS Lambda function?
For example:
var handler = new HttpClientHandler {
Credentials = new NetworkCredential("username", "password", "domain")
};
var httpClient = new HttpClient(handler);
var content = new StringContent("<test>test</test>", Encoding.UTF8, "application/xml");
var response = await httpClient.PostAsync("http://someurl", "content");
The target url returns 401 Unauthorized and it looks like the NetworkCredentials haven't been passed through.
The Lambda has been granted the role AWSLambdaFullAccess.
When executed locally, this code with the same credentials works as expected.

Why do I get 'Proxy Authentication Required'when I've set up proxy credentials in c#

I found several questions about this but they seem to resolve windows authentication. I have custom users and passwords and this code works with other existing proxies. Now since a week we use new proxy servers that use {Basic realm="Private Proxies - Password Auth"} and the code does not work.
var user = "********";
var pass = "********";
var port = "********";
var ip = "********";
var url = "********";
var baseUrl = "********";
NetworkCredential cr = new NetworkCredential(user, pass);
cr.Domain = ip;
WebProxy proxy = new WebProxy(ip + ":" + port) { BypassProxyOnLocal = false, Credentials = cr, UseDefaultCredentials = false};
HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = proxy;
handler.UseProxy = true;
HttpClient httpClient = new HttpClient(handler);
httpClient.BaseAddress = new Uri(baseUrl);
var result = httpClient.GetAsync(url).Result;
Console.WriteLine(result.Content.ReadAsStringAsync().Result);
Console.Read();
I have tested the credentials with Firefox and there the proxies work after I provide the credentials in a popup. I set the NetworkCredential inside the proxy, but when I do a request it just returns 407: Proxy Authentication Required.
I tried to set the Proxy-Authorization header manually. It still does not work.
Does anyone know how to fix this!?
You need to fill Proxy-Authorization header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Proxy-Authorization
Also, look at this question: Proxy Basic Authentication in C#: HTTP 407 error

Trouble downloadig an thumbnail image in O365 Video using C#

I am running into an odd issue with trying to access a thumbnail image stored on O365 video via C#. I can access the REST API with no issue at all, I just add the Authentication: Bearer <token> to the header and I am off an running. The trouble is with a basic image URL that I get back from a specific video.
https://<mytenant>.sharepoint.com/portals/Channel1/pVid/myvideo.mp4.PNG?VideoPreview=1
When I access that URL from a browser it works 100% of the time. When I try to access it via the httpclient object, I am getting a 401 Unauthorized error.
The best I can figure is that the authorization header token is not being honored when accessing a basic URL. Which makes me thing that I need something else like a cookie? However I cannot seem to figure out which one. Looking for any advice :)
Pass credentials instead and yes you need an authentication cookie. Here is a sample:
private static async Task<string>getWebTitle(string webUrl)
{
//Creating Password
const string PWD = "softjam.1";
const string USER = "bubu#zsis376.onmicrosoft.com";
const string RESTURL = "{0}/_api/web?$select=Title";
//Creating Credentials
var passWord = new SecureString();
foreach (var c in PWD) passWord.AppendChar(c);
var credential = new SharePointOnlineCredentials(USER, passWord);
//Creating Handler to allows the client to use credentials and cookie
using (var handler = new HttpClientHandler() { Credentials = credential })
{
//Getting authentication cookies
Uri uri = new Uri(webUrl);
handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
//Invoking REST API
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
string jsonData = await response.Content.ReadAsStringAsync();
return jsonData;
}
}
}

Categories