I am looking to create a C# application that will report on the connections that we make to customers. I am looking into the TeamViewer API, but I cannot get the code below to authenticate:
string accessToken = "xxxxxxxxxxxxxxxxxxx";
string apiVersion = "v1";
string tvApiBaseUrl = "https://webapi.teamviewer.com";
string address = tvApiBaseUrl + "/api/" + apiVersion + "/reports/connections";
try
{
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Headers.Add("Bearer", accessToken);
request.Method = "GET";
WebResponse webResp = request.GetResponse();
}
catch (Exception)
{
// Do nothing for now
}
Use fiddler and make sure your requests include the authorization header.
All API requests need to include the "Authorization" header if the API function requires an access token.
Example
GET /api/v1/users HTTP/1.1
Host: webapi.teamviewer.com
Authorization: Bearer 54213-2YotnFZFEjr1zCsicMWp
Also examine what they are sending you back, it may provide a clue.
UPDATE
Try this change
request.Headers.Add("Authorization", "Bearer " + accessToken);
Related
I have been trying to make a post request with C# using Webclient. I was getting 400 bad request.When I adjusted the headers, and added authorization to it,I started getting 401 authorization error.Now i commented out the authorization, 400 bad request is back. So my question is: when it was returning 400, does it mean the server authenticated me and that something might be wrong with my json or can 400 be returned even before authentication is done? Below is my code.
public static string Post(string json, string encoded){
try{
string url = "https://blah/rest/api/blah";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
IWebProxy wp = WebRequest.DefaultWebProxy;
wp.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = wp;
//client.Headers[HttpRequestHeader.Authorization] = "Basic " + encoded;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers[HttpRequestHeader.Accept] = "application/json";
var response = client.UploadString(url, "POST",json);
return response
}
catch(Exception e){
return e
}
}
This is my C# code:
var url = "http://10.2.0.2/api";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Referer = url;
request.Host = "wwww.abc.com";
request.Accept = "*/*";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
while I run the code, and open fiddler to capture request,
I found fiddler discard header: Host,
so my IIS returned an error!
How did I avoid it?
Why fiddler discards Host but keep other headers?
Question: another
was header be changed, my question was header be discard.
I found my solution, open FiddlerScript, and add these script:
static function OnBeforeRequest(oSession: Session) {
var sOverride = oSession["X-Original-Host"];
if (!String.IsNullOrEmpty(sOverride))
{
oSession.oRequest.headers["Host"] = sOverride;
}
static void Main()
{
Console.WriteLine("10504: " + TestURL("business.lynchburgchamber.org"));
Console.WriteLine("Google: " + TestURL("google.com"));
Console.ReadKey();
}
static string TestURL(string baseURL)
{
try
{
string httpsURL = "https://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpsURL);
return request.RequestUri.Scheme;
}
catch
{
string httpURL = "http://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpURL);
return request.RequestUri.Scheme;
}
}
I am testing urls to see if they are either http or https. My idea was to use an HttpWebRequest to check if the https request goes through, and if it fails go for the http. My problem is that if I go to https://business.lynchburgchamber.org in my browser if fails to connect, but my web request in my program returns https. Anyone have a better way to do this?
Your problem is, that you are not issuing the request, your just creating and instance to do the request.
So what you actually have to do is this:
static string TestURL(string baseURL)
{
try
{
string httpsURL = "https://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpsURL);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return request.RequestUri.Scheme;
}
catch
{
string httpURL = "http://" + baseURL;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpURL);
//request.Method = "GET";
//HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return request.RequestUri.Scheme;
}
}
The second issuing could be also done, but as I think you are intending to check if a site has https, this would be misleading.
But keep in mind that it will return http if there is no internet connection!
Add a Request.GetResponse to really check if you have a Response from the URL:
var rt=request.GetResponse();
To be really sure, after this you can check the port
rt.ResponseUri.Port
if it returns 80 it must be Http,443 for https
I am building a WCF that encapsulates Google OAuth 2.0.
The plan: Client calls WCF endpoint which then redirects to the Google Sign In page for user authentication. On successful authentication, Google kicks back to the redirect URI and returns the Access Token in the response.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class AdWordsOAuthService : IOAuthService
{
public string AuthenticateAndGetRefreshToken()
{
string refreshToken = string.Empty;
try
{
AuthenticateUser();
}
catch (Exception ex)
{
throw;
}
return refreshToken;
}
private void AuthenticateUser()
{
// build the SOAP header here...
string authUrl = "https://accounts.google.com/o/oauth2/auth"; //redirect to this url
string postData = "response_type=code"
+ "&client_id=" + HttpUtility.UrlEncode("9999999999999.apps.googleusercontent.com")
//+ "&client_secret=" + HttpUtility.UrlEncode("dsflkdfsljkdfskjldskjlfds")
+ "&redirect_uri=" + HttpUtility.UrlEncode("http://localhost:50306/NextOAuthService/AdWordsOAuthService/AuthenticateAndGetRefreshToken")
+ "&scope=" + HttpUtility.UrlEncode("https://adwords.google.com/api/adwords")
+ "&access_type=offline";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//handle webrequest stuff...
var request = (HttpWebRequest)WebRequest.Create(authUrl);// + postData);
if (request != null)
{
request.Method = "POST";
request.Timeout = 20000;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length; // byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//attempt to redirect to the Adwords OAuth URL: https://adwords.google.com/api/adwords&?response.....blah blah
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.RedirectKeepVerb;
WebOperationContext.Current.OutgoingResponse.Location = response.ResponseUri.AbsoluteUri;
return;
}
}
}
What's Actually Happening: When the code attempts the redirect, I get following exception:
The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (application/soap+xml;> charset=utf-8)
When I examine the response (using fiddler), the response contains the actual HTML code for the Google OAuth Sign In page. So, instead of redirecting the WCF to the url, I am instead receiving an html response containing the page source.
How do I get around this and force the redirect?
I think you are miss understanding the calls a bit. The First URL that you are building there is the one that you should be displaying to the user asking if they want to let you access there data.
You need to wait for them to except. You need to deal with the Authentication Code. Google 3 Legged OAuth2 Flow
You should consider using Googles dot net client lib. It will handle all this for you.
I have a problem when I do an httprequest and the remote server responds with a redirect and some additional query parameters. The problem is that the additional parameters is empty on certain enviroments.
When I run the code in a test-environment the parameters is not empty.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri(ConfigurationManager.AppSettings["proxyUrl"]);
myProxy.Address = newUri;
request.Proxy = myProxy;
request.Timeout = Int32.Parse(ConfigurationManager.AppSettings["PBVtimeout"]);
request.AllowAutoRedirect = true;
request.MaximumAutomaticRedirections = 2;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(myCertificateValidation);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
log.Debug("PathAndQuery: " + response.ResponseUri.PathAndQuery);
log.Debug("Statuscode: " + response.StatusCode);
log.Debug("Statusdescription: " + response.StatusDescription);
Uri uri = response.ResponseUri;
NameValueCollection qscol = ParseQueryString(uri.Query);
return qscol["Status"] + qscol["Status_code"];
I log StatusCode, StatusDescription and the PathAndQuery of the response. StatusCode and StatusDescription is "OK" in both enviroments but the PathAndQuery looks like this:
Faulty environment: localhost/Service
Correct environment: localhost/Service?Merchant_id=1345&Version=2&Customer_refno=269932&Status=E&Status_code=48
As you can see the faulty enviroments is missing the parameters.
My initial thought was that it was a problem with a firewall "cleaning" the redirect response. But when I did the http request in an ordninary web browser it worked fine.
The code is in C# .Net 2.0 and it runs on a Windows 2003 server.
Any ideas where the problem could be?