How to upload to YouTube using the API via a Proxy Server - c#

I am building an application which will allow users to upload videos to a specific account on you tube.
I have followed the examples on http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html for direct upload however I am now getting a 407 proxy authentication required when request.Upload(newVideo) is called.
I've found an example for the Google Calendar Service using a proxy ( http://code.google.com/p/google-gdata/wiki/WebProxySetup )but can't seem to work out how to refactor it for YouTube.
Any ideas?

It sounds like your proxy requires credentials. Credentials have to be supplied in code; I'm currently trawling the source for the Google API to find it, since they have their own custom request objects.
In the mean time, you might get it to work by simply not using the default proxy. Modify your app.config or web.config to insert this at the correct location:
<configuration>
<system.net>
<defaultProxy>
<proxy usesystemdefault="false"/>
</defaultProxy>
</system.net>
</configuration>
Edit:
Ok, after doing some digging, here's how I think you'd refactor the instructions you linked for your specific request. Assuming you've already created a YouTubeRequest as follows:
YouTubeRequest request = new YouTubeRequest(settings);
Here are the refactored instructions from your link:
YouTubeRequest request = new YouTubeRequest(settings);
GDataRequestFactory f = (GDataRequestFactory) request.Service.RequestFactory;
IWebProxy iProxy = WebRequest.DefaultWebProxy;
WebProxy myProxy = new WebProxy(iProxy.GetProxy(query.Uri));
// potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialsCache.DefaultCredentials;
myProxy.UseDefaultCredentials = true;
f.Proxy = myProxy;
Here are my sources:
http://google-gdata.googlecode.com/svn/docs/folder56/T_Google_YouTube_YouTubeRequest.htm
http://google-gdata.googlecode.com/svn/docs/folder53/P_Google_GData_Client_FeedRequest_1_Service.htm
http://google-gdata.googlecode.com/svn/docs/folder19/P_Google_GData_Client_Service_RequestFactory.htm

Using the code provided by Randolpho I managed to get the code to successfully call YouTube. I managed to simplfy the code more to
YouTubeRequest request = new YouTubeRequest(settings);
GDataRequestFactory f = (GDataRequestFactory)request.Service.RequestFactory;
WebProxy myProxy = new WebProxy("http://proxy-server:port/", true);
myProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
f.Proxy = myProxy;
The code will be running with a service account with access to the internet so I shouldn't need to provide a username and password in the code.

Related

Generated WCF SOAP client uses current user for windows authentication instead of given credentials

I'm kind of new to the whole WCF and SOAP topic so please be kind.
I'm using a generated SOAP Client with .net6. In another project we successfully worked with the same Web Service using the old .net Framework 2.0 Web References and the same credentials.
Strange enough everything seemed to work fine at first. Until I realized, that it does not use the given credentials to authenticate. Instead it authenticates with my own domain user.
I also tried to get it to work with explicitly setting the binding with a BasicHttpBinding but I only could get the same broken logic to work or I got various authentication/protocol/security errors.
So it seems the authentication is basically working. It just doesn't use the provided credentials. So my question is: How can I configure it to work with the provided identity?
I also found out that it might have anything to do with a cached Windows token. But how can I get rid of it. How to prevent caching in the first place?
EDIT:
Specified the variable types explicitly.
string url = "http://someServer/AdministrationService.asmx";
AdministrationServiceSoapClient client = new AdministrationServiceSoapClient(
AdministrationServiceSoapClient.EndpointConfiguration.AdministrationServiceSoap,
url);
WindowsClientCredential credential = client.ClientCredentials.Windows;
credential.ClientCredential.UserName = "username";
credential.ClientCredential.Password = "password";
credential.ClientCredential.Domain = "DOMAIN";
GetServerInfoRequest getServerInfoRequest = new GetServerInfoRequest
{
// some stuff set here
};
GetServerInfoRequest getServerInfoReply = await client.GetServerInfoAsync(getServerInfoRequest);
As far as I know, BasicHttpBinding has security disabled by default, but can be added setting the BasicHttpSecurityMode to a value other than None in the constructor. It can be configured according to the instructions in BasicHttpBinding and BasicHttpBinding Constructors.
By default, setting up client credentials involves two steps: determining the type of client credential required by the service and specifying an actual client credential, as described in this document.
After waiting a day it is working. It seems that the cached credentials became invalid somehow.
Strange enough the simple service creation from above is not working anymore. Instead I have to use the following.
var client = new AdministrationServiceSoapClient(
new BasicHttpBinding()
{
Security = new BasicHttpSecurity()
{
Mode = BasicHttpSecurityMode.TransportCredentialOnly,
Message = new BasicHttpMessageSecurity()
{
ClientCredentialType = BasicHttpMessageCredentialType.UserName,
},
Transport = new HttpTransportSecurity()
{
ClientCredentialType = HttpClientCredentialType.Windows,
ProxyCredentialType = HttpProxyCredentialType.Windows,
}
},
},
new EndpointAddress(url));

RestSharp isn't consistent when calling wordpress/woocomerce site

In my dev environment, I have a wordpress/woocommerce site locally all hosted under IIS.
Using the following code restsharp works:
var fullEndPoint = string.Concat(site, "/wp-json/wc/v3/", endpoint)
var client = new RestSharp.RestClient(fullEndPoint)
{
Authenticator = OAuth1Authenticator.ForProtectedResource(consumerkey, woosecret, "", "")
};
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(serializedData);
client.Execute(request);
When I change the fullEndPoint, consumerkey and woosecret to be our main test site which mirrors our live site (running on apache/linux), I receive
Sorry you are not allowed to create Resource.
If I post to our test site the same data using postman, it goes through and works.
For the purposes of testing, if I then change the above declaration of client to be:
var client = new RestClient("https://wordpress.mytestsite.com/wp-json/wc/v3/products?oauth_consumer_key=ck_a24ad9ddea2d9fe71d9172c415fd51b4dc83a6dc&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1627038994&oauth_nonce=T9gfeZGdmNx&oauth_version=1.0&oauth_signature=OJB1TBpLpA%2Bet0A%2FDFbozOT9nf8%3D");
where fullendpoint is the code shown in postman's code windows for Restsharp, again the code works, so I know the error is misleading. So Why doesn't restsharp work in the initial way for me when I point to my test site?
Edit:
If I change client such that I'm now setting it up as:
var client = new RestSharp.RestClient(fullEndPoint)
{
Authenticator = OAuth1Authenticator.ForClientAuthentication(consumerkey, woosecret, username, password)
};
where username and password equal the user set up in woo commerce against the consumer key for read/write access, I still receive an access denied error

OneDrive API with C#, get authentication code programmatic

I have to write an application, no matter what language (c#, Java, shell, python ...) that can connect to OneDrive and then uploads file.
Following the OneDrive API I found that i need in one step to go to the browser (manually and to post a url that combines client_id and client_security to get an authentication code so i can connect my client with it to get the access token. (oAuth2 protocol)
I need to get the access_token pragmatically, i don't need any manual step to be involved.
I tried in c# to use the WebBrowser component to navigate to the url and to get the access token, I found that the browser stays in the same url and not getting the final url that includes the auth_code!
My code looks like:
// Initialize a new Client (without an Access/Refresh tokens
var client = new Client(options);
// Get the OAuth Request Url
var authRequestUrl = client.GetAuthorizationRequestUrl(new[] { Scope.Basic, Scope.Signin, Scope.SkyDrive, Scope.SkyDriveUpdate });
// TODO: Navigate to authRequestUrl using the browser, and retrieve the Authorization Code from the response
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.ScrollBarsEnabled = false;
wb.ScriptErrorsSuppressed = true;
wb.Navigate(authRequestUrl);
Console.WriteLine(wb.Version);
while (wb.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
wb.Document.InvokeScript("evt_Login_onload(event)");
Uri myUrl = wb.Url;
Anyone can help with fixing this, or maybe suggest other ideas please?
Thanks in Advance!
It looks like you're creating a Windows desktop app using C#. There's actually an example at https://msdn.microsoft.com/en-us/library/hh826529.aspx for using the WebBrowser class to get the authorization code, then the token, then make an API. In short, you'll first need to send a request to the following URL with your client_id and scopes.
https://login.live.com/oauth20_authorize.srf?client_id=YOUR_CLIENT_ID&scope=YOUR_SCOPE_STRING&response_type=code&redirect_uri=https://login.live.com/oauth20_desktop.srf
In the response, you'll get the authorization code which you'll need to use to send another request to with your client_id, client_secret, authorization code like the following.
https://login.live.com/oauth20_token.srf?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&redirect_uri=https://login.live.com/oauth20_desktop.srf&code=AUTHORIZATION_CODE&grant_type=authorization_code
When you finally receive the access token, you can make requests to the API using your access token similar to the following.
"https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN". The "me" can be changed to any other folder or directory.
I hope that helps.
dont u think the scope u provided are wrong, they should be wl.basic, wl.signin, and if ur using new onedrive api then it should be onedrive.readonly or onedrive.readwrite
if ur using liveconnect api for the purpose of using onedrive then scope should be wl.skydrive or wl.contacts_skydrive or wl.skydrive_update
depending upon ur uses (refer https://msdn.microsoft.com/en-us/library/hh243646.aspx)
and can u more elaborate how ur trying to get the access_token, from above it is quite confusing to me
Have you solved you issue?
Have you tried to use the LiveSDK to authenticate?
Have a look at my question there, it might help you :
Onedrive API vs LiveSDK
I have used the following code, after installing both the LiveSDK and the OneDrive SDK, and this does not require any login after the first authorization. However it "may" have to be a RT app (windows store or windows phone store)
var authClient = new LiveAuthClient();
var authResult = await authClient.LoginAsync(new string[] {
"wl.signin", "onedrive.readwrite", "onedrive.appfolder"});
if (authResult.Session == null)
throw new InvalidOperationException("You need to sign in and give consent to the app.");
var Connection = new ODConnection("https://api.onedrive.com/v1.0",
new MicrosoftAccountAuthenticationInfo() { TokenType = "Bearer",
AccessToken = odArgs.Session.AccessToken });
Toan-Nguyen's answer almost helps me. On the step 2 (when I should send a request with authorization code) I get the response with error "Public clients can't send client secret". This answer said it's neccessary to remove the attribute client_secret from url.

How to use proxy at LinqToTwitter

I want to use proxy when using LinqToTwitter. I downloaded source code but there is no proxy feature at HttpWebRequest object. I don't understand how is this happening.
Here what i mean
This is inside TwitterExecute.cs.
I want to modify it in a way that i can set different proxy for each thread.
So my question is how to modify to use proxy server when posting a status tweet etc?
The proxy you're looking at supports Silverlight. I recently added a Proxy property to ITwitterAuthorizer:
https://linqtotwitter.codeplex.com/SourceControl/latest#LinqToTwitterAg/OAuth/ITwitterAuthorizer.cs
This is type WebProxy, which you can assign whenever you instantiate an authorizer:
http://msdn.microsoft.com/en-us/library/system.net.webproxy(v=vs.110).aspx
Updated Sample Code:
var auth = new SingleUserAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = srtwitterConsumerKey,
ConsumerSecret = srtwitterConsumerSecret,
OAuthToken = srtwitterOAuthToken,
AccessToken = srtwitterAccessToken
}
};
auth.Proxy = new WebProxy("http://proxyserver:80/",true);
var twitterContext = new TwitterContext(auth);
I've also seen where people have used configuration files to specify their proxy since LINQ to Twitter v2.1.x uses HttpWebRequest:
http://msdn.microsoft.com/en-us/library/kd3cf2ex(v=vs.110).aspx
LINQ to Twitter v3.0 supports IWebProxy on IAuthorizer:
https://linqtotwitter.codeplex.com/SourceControl/latest#LinqToTwitterPcl/Security/IAuthorizer.cs
I just found the folder called LinqToTwitterProxy inside the LinQToTwitter Package. It contains workaround to bypass the proxy.
I hope that will helpout to resolve your issue.

Unable to connect to a web service

I am able to access the web service from the web browser but on the same computer if I try to connect to the web service through code I get a The remote server returned an error: (407) Proxy Authentication Required. error.
I have supplied all the credentials required. Here is my code -
MyWebService objWS = new MyWebService(); // my Web service object
// My credentials
System.Net.NetworkCredential cr = new System.Net.NetworkCredential(MyDomainUserName, UserPassword, DomainController);
System.Net.WebProxy pr = new System.Net.WebProxy(ProxyServer, ProxyPort);
pr.Credentials = cr; //Using my credentials for the local proxy
// Web Service credentials
System.Net.NetworkCredential cr1 = new System.Net.NetworkCredential("My_WebService_UserName", "My_WebService_Pwd");
objWS.Credentials = cr1; // Using WebService credentials to the WS object
//objWS.Credentials = CredentialCache.DefaultCredentials; // I even tried Using default credentials but this didn't help.
objWS.Proxy = pr;
Object result = objWS.WebMethod1(param1,param2,param3);
But, this throws an error - The remote server returned an error: (407) Proxy Authentication Required.
Any idea, what am I doing wrong here? Thanks.
You need to update your config file like this to fix this problem.
<system.net>
<defaultProxy useDefaultCredentials="true"> </defaultProxy>
</system.net>
It isn't clear in this blog post, but this isn't either/or. Both things are required to fix your problem.
http://blogs.msdn.com/b/jpsanders/archive/2009/03/24/httpwebrequest-webexcepton-the-remote-server-returned-an-error-407-proxy-authentication-required.aspx
You get this error because you are trying to access the service from behind a proxy.
Try to use this code (you probably only need the last line):
//Set the system proxy with valid server address or IP and port, for example.
System.Net.WebProxy pry = new System.Net.WebProxy("172.16.0.1",8080);
//The DefaultCredentials should be enough.
pry.Credentials = CredentialCache.DefaultCredentials;
GlobalProxySelection.Select = pry;
This means that your proxy needs some credentials(user name and pasword.) Figure out what they are and set them on pry.

Categories