Proxy Authentication for Twitterizer2 in C# - c#

Currently the Code i am using to update twitter status is as follows...
public static void SendMessage(string message)
{
try
{
tokens = new OAuthTokens();
tokens.AccessToken = "Some Token";
tokens.AccessTokenSecret = "Some Secret";
tokens.ConsumerKey = "Some Key";
tokens.ConsumerSecret = "Some CSecret";
TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message);
}
Please spoon feed me on how to authenticate myself for a proxy on 10.0.0.21 and port 3128 requesting for a username and password.
I am able to access the net and download webpages from C# application using the following code but am not able to update twitter from twitterizer due to this issue...
WebClient w = new WebClient();
WebProxy p = new WebProxy("10.0.0.21", 3128);
p.Credentials = new NetworkCredential("UserName", "Password");
w.Proxy = p;
string s = w.DownloadString(SomeUrl);
How to do the same in twitterizer2 package...? Its not taking from IE because Authentication is required for this proxy.
I am not sure of how to modify the configuration file. One more issue is i will not run this application always behind a proxy..mostly it will be run outside a proxy.
Please help. Thanks.

Twitterizer handles proxy settings in 3 ways. They are, in order that Twitterizer chooses which to use:
Every method has an optional parameters argument. They are all based on a single class that has a proxy property that allows you to provide a web proxy exactly the same way that you did in your example. This is good if you have a small amount of Twitter integration, but obviously not great for larger applications.
You can specify your proxy in your configuration file using the <defaultproxy> element. Good for whole applications, but unfortunately won't handle the use of authentication.
The default IE settings are used.
Since your proxy requires authentication, the only option is to specify the optional properties class to every method.
For example:
public static void SendMessage(string message)
{
try
{
tokens = new OAuthTokens();
tokens.AccessToken = "Some Token";
tokens.AccessTokenSecret = "Some Secret";
tokens.ConsumerKey = "Some Key";
tokens.ConsumerSecret = "Some CSecret";
WebProxy p = new WebProxy("10.0.0.21", 3128);
p.Credentials = new NetworkCredential("UserName", "Password");
StatusUpdateOptions options = new StatusUpdateOptions();
options.Proxy = p;
TwitterResponse<TwitterStatus> tweetResponse = TwitterStatus.Update(tokens, message, options);
}
}

Related

How to create CallCredentials from SslCredentials and token string

I am porting a gRPC client from python to c#. Both the python client and the c# client are using the gRPC Framework from grpc.io.
The python client uses the following code to open a secure, non-authenticated channel, which it then uses to procure a token string, which it then uses to create call credentials with the grpc.composite_channel_credentials() function:
channel = grpc.secure_channel(url_server_address, ssl_creds)
stub = gateway.GatewayStub(channel)
# Acquire access token via password authentication
pw_cmd = gateway.PasswordAuthenticateCmd(account_name=url.username, password=url.password)
auth_rsp = stub.PasswordAuthenticate(pw_cmd)
# Open a secure, authenticated channel
auth_creds = grpc.access_token_call_credentials(auth_rsp.access_token)
composite_creds = grpc.composite_channel_credentials(ssl_creds, auth_creds)
channel = grpc.secure_channel(url_server_address, composite_creds)
stub = gateway.GatewayStub(channel)
In c#, I have been able to compile the protocol buffer definitions, and connect with the generated client to successfully acquire the access token:
SslCredentials secureChannel = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel channel = new Channel(ServerURL, PortNum, secureChannel);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(channel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
Console.WriteLine(response.AccessToken);
From here, however, I can't find the c# analog to the grpc.composite_channel_credentials() function to take the SslCredentials and the access token string to create combined credentials.
None of the examples here https://grpc.io/docs/guides/auth.html here use a token string, and I haven't been able to find any other examples out there.
What you're looking for is:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/CallCredentials.cs#L49 and https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Core/ChannelCredentials.cs#L67.
Feel free to also look at:
https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58
I solved my problem using CallCredentials.FromInterceptor().
The grpc.access_token_call_credentials() python call adds an authorization entry to the metadata, and sets its value to "Bearer " + AccessToken, so I just had to do the same:
SslCredentials secureCredentials = new SslCredentials(File.ReadAllText(SSLCertificatePath));
Channel secureChannel = new Channel(ServerURL, PortNum, secureCredentials);
var client = new GrpcClient(new Grpc.Gateway.GatewayClient(secureChannel));
var response = client.client.PasswordAuthenticate(new PasswordAuthenticateCmd() { AccountName = UserName, Password = UserPassword });
var accessTokenCredentials = CallCredentials.FromInterceptor(new AsyncAuthInterceptor((context, metadata) =>
{
metadata.Add("authorization", "Bearer " + passwordResponse.AccessToken);
return TaskUtils.CompletedTask;
}));
var authenticatedCredentials = ChannelCredentials.Create(secureCredentials, accessTokenCredentials);
Channel authenticatedChannel = new Channel(hostURL, hostPort, authenticatedCredentials);
As Jan pointed out in his answer, there is a function in the Grpc.Auth namespace that does the same thing as the function that I wrote: https://github.com/grpc/grpc/blob/c5311260fd923079637f5d43bd410ba6de740443/src/csharp/Grpc.Auth/GoogleAuthInterceptors.cs#L58

DocuSign API and DocumentPDFs docPDFs = apiService.RequestDocumentPDFs(envelopeID);

I am using the code below to connect to DocuSign API.
WHAT AM I doing wrong, I keep getting Username and Password not correct when they are!
String auth = "<DocuSignCredentials><Username>john.connolly#lechase.com</Username><Password>password</Password><IntegratorKey>20be051c-4c25-46c1-b0f1-1f10575a2e40</IntegratorKey></DocuSignCredentials>";
DSAPIServiceSoapClient client = new DSAPIServiceSoapClient("DSAPIServiceSoap");
using (System.ServiceModel.OperationContextScope scope = new System.ServiceModel.OperationContextScope(client.InnerChannel))
{
System.ServiceModel.Channels.HttpRequestMessageProperty httpRequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
System.ServiceModel.OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = httpRequestProperty;
EnvelopeStatus status = client.RequestStatusEx("12d46951-1f1c-48cd-9a28-e51685d67ccd");
Console.Out.WriteLine("Subject: " + status.Subject);
}
Since you use the (Legacy Header Authentication uses the X-DocuSign-Authentication header):
Use the Authentication: login method
to retrieve the account number and the baseUrl for the account.
The url for the login method is www.docusign.net for production and
demo.docusign.net for the developer sandbox. The baseUrl field is
part of the loginAccount object. See the docs and the loginAccount
object
The baseUrl for the selected account, in production, will start with na1, na2, na3, eu1, or something else. Use the baseUrl that is
returned to create the basePath (see the next step.) Use the
basePath for all of your subsequent API calls.
As returned by login method, the baseUrl includes the API version and account id. Split the string to obtain the basePath, just the
server name and api name. Eg, you will receive
https://na1.docusign.net/restapi/v2/accounts/123123123. You want
just https://na1.docusign.net/restapi
Instantiate the SDK using the basePath. Eg ApiClient apiClient = new ApiClient(basePath);
Set the authentication header as shown in the examples by using Configuration.Default.AddDefaultHeader Ref.
Sample Code: Try a verbatim string for your auth string.
string auth = #"<DocuSignCredentials>
<Username>john.connolly#lechase.com</Username>
<Password>S3cre+p455w0Rd</Password>
<IntegratorKey>20be051c-4c25-46c1-b0f1-1f10575a2e40</IntegratorKey>
</DocuSignCredentials>";
DSAPIServiceSoapClient apiService = new DSAPIServiceSoapClient();
using (var scope = new System.ServiceModel.OperationContextScope(apiService.InnerChannel))
{
var httpRequestProperty = new System.ServiceModel.Channels.HttpRequestMessageProperty();
httpRequestProperty.Headers.Add("X-DocuSign-Authentication", auth);
System.ServiceModel.OperationContext.Current.OutgoingMessageProperties[System.ServiceModel.Channels.HttpRequestMessageProperty.Name] = httpRequestProperty;
EnvelopeStatus envStatus = apiService.CreateAndSendEnvelope(envelope);
return envStatus.EnvelopeID;
}

Amazon S3 Unable to find credentials in C#

I'm trying to upload an image file to aws s3 storage and get back that image URL. I'm using secret key and access key to create credentials. But when the program runs it it says
"Unable to find credentials" .
Here is my code which i used.
public string sendMyFileToS3(string from,string to, string bucketName, string fileName)
{
BasicAWSCredentials awsCreds = new BasicAWSCredentials(bucketName, fileName);
AmazonS3Client client = new AmazonS3Client(awsCreds);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = bucketName;
request.Key = fileName;
request.FilePath = from;
utility.Upload(request);
string urlString = "";
GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = fileName,
Expires = DateTime.Now.AddYears(2)
};
urlString = client.GetPreSignedURL(request1);
Console.WriteLine(urlString);
File.Move(from, to);
return urlString ;
}
In order to create an S3 Client you need to provide your credentials, the region and endpoint:
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = "s3.amazonaws.com";
config.RegionEndpoint = Amazon.RegionEndpoint.GetBySystemName("us-east-1");
client = new AmazonS3Client(credentials, config);
The possible regions are listed here, and depend on where you created your bucket being us-east-1 the default value.
While the possible endpoints are this three:
s3.amazonaws.com
s3-accelerate.amazonaws.com
s3-accelerate.dualstack.amazonaws.com
The first one being the standard one since the others need you to configure your bucket like it's explained here.
I am going to take a guess and say you have a conflict between the credentials your app is using and other credentials you may have installed onto your dev or test machine, i.e. in the credentials file or your app.config.
I would check and make sure you are only using a single method to provide those credentials to the program.
THis link shows the priority the SDK will look for the credentials:
http://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html

DocuSign: Error calling CreateEnvelope

I have the following code for adding a new Envelope with a local file:
EnvelopeDefinition envelope = new EnvelopeDefinition
{
Status = "sent"
};
// Get the contract file
Byte[] bytes = File.ReadAllBytes("[Local Filename]");
// Add a document to the envelope
DocuSign.eSign.Model.Document doc = new DocuSign.eSign.Model.Document();
doc.DocumentBase64 = System.Convert.ToBase64String(bytes);
doc.Name = contract.FileName;
doc.DocumentId = "1";
envelope.Documents = new List<DocuSign.eSign.Model.Document>();
envelope.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Email = recipientEmail;
signer.Name = recipientName;
signer.RecipientId = "1";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
signHere.DocumentId = "1";
signHere.PageNumber = "1";
signHere.RecipientId = "1";
signHere.XPosition = "100";
signHere.YPosition = "150";
signer.Tabs.SignHereTabs.Add(signHere);
envelope.Recipients = new Recipients();
envelope.Recipients.Signers = new List<Signer>();
envelope.Recipients.Signers.Add(signer);
DocuSignAuthentication Creds = new DocuSignAuthentication
{
Username = "[My Username]",
Password = "[My Password]",
IntegratorKey = "[My Integration Key]"
};
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi/v2/accounts/XXXXXXX");
string authHeader = JsonConvert.SerializeObject(Creds);
DocuSign.eSign.Client.Configuration cfg = new DocuSign.eSign.Client.Configuration(apiClient);
cfg.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
EnvelopesApi envelopeApi = new EnvelopesApi(cfg);
EnvelopeSummary response = envelopeApi.CreateEnvelope("XXXXXXX", envelope);
The server returns a very little information in the error:
[ApiException: Error calling CreateEnvelope: ]
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelopeWithHttpInfo(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in
Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2606
DocuSign.eSign.Api.EnvelopesApi.CreateEnvelope(String accountId, EnvelopeDefinition envelopeDefinition, CreateEnvelopeOptions options) in Y:\dev\SDKs\csharp\sdk\src\main\csharp\DocuSign\eSign\Api\EnvelopesApi.cs:2532
[Rest of the stack trace relates to our code]
If we try to use fiddler to capture any error messages from the server, the error becomes:
Could not establish trust relationship for the SSL/TLS secure channel
Is there anyway to get a more information about what's wrong with our request? Or is there an un-encrypted developer endpoint available to work through these kinds of issues? Any help you can spare would be greatly appreciated.
The error "Could not establish trust relationship for the SSL/TLS secure channel" means that the HTTPRequest call from the client (which can be your server, but is a client in the sense that it made the HTTPRequest) to the server (DocuSign in this case) could not use TLS over SSL (https:// address) to ensure that there's a certificate that allows to encrypt the information in the HTTPRequest and HttpResponse. This can happen for a variety of reasons including not having the current version of TLS on the client as well as having the wrong certificate or other issues with the network. I would recommend trying to make this call from a different server, potentially outside your corporate network to isolate the problem. Also, check the version of TLS to ensure it's at least 1.1

What is the verifier in DotNetOpenAuth's DesktopConsumer ProcessUserAuthorization?

I am new to DotNetOpenAuth and I can't find what value to use as the verifier in ProcessUserAuthorization.
What I want to achieve is to log in with my user credentials into an application (called UserVoice) that uses OAuth. Here's what my code looks like:
string requestToken;
var authorizeUri = consumer.RequestUserAuthorization(new Dictionary<string, string>(), null, out requestToken).AbsoluteUri;
var verifier = "???";
var accessToken = consumer.ProcessUserAuthorization(requestToken, verifier).AccessToken;
consumer.PrepareAuthorizedRequest(endpoint, accessToken, data).GetResponse();
I tried to use my username, my password, my consumer key, my consumer secret, but nothing seems to work. Does someone know which value I should use as the verifier?
Thanks
I finally found a way to log in to UserVoice with DotNetOpenAuth. I think UserVoice's implementation of OAuth wasn't standard, but I was able to do it during this:
var consumer = new DesktopConsumer(this.GetInitialServiceDescription(), this._manager)
string requestToken;
consumer.RequestUserAuthorization(null, null, out requestToken);
// get authentication token
var extraParameters = new Dictionary<string, string>
{
{ "email", this._email },
{ "password", this._password },
{ "request_token", requestToken },
};
consumer = new DesktopConsumer(this.GetSecondaryServiceDescription(), this._manager);
consumer.RequestUserAuthorization(extraParameters, null, out requestToken);
Where GetInitialServiceDescription returns the good request description, and GetSecondaryServiceDescription is a hacked version and returns the authorize endpoint in place of the request token endpoint. The "request_token" returned this way (which is not really a normal request_token from my understanding of OAuth) can then be used as an access token for PrepareAuthorizedRequest.
The verifier is the code that UserVoice would display onscreen after the user has said they want to authorize your app. The user must copy and paste this verifier code from the web site back into your application's GUI, so that it can then pass it into the ProcessUserAuthorization method.
This is only required in OAuth 1.0a (not 1.0), and is there to mitigate certain exploitable attacks that were discovered in 1.0. In your ServiceProviderDescription be sure you specify that the service is a 1.0a version (if in fact Uservoice supports that) so that DNOA will communicate to Uservoice that it should create a verifier code.
Incidentally, various tricks including scanning process titles or hosting the browser within your own app can eliminate the manual user copying the verify code step by having your app automatically copy it for him.
The verifier is also used when the Authorization is done via WebAPI and you do not have a redirect displayed in a browser. In this you just send your AuthentificationRequest via code and get the verifier as a json-string without any user interaction.
In this case the process (for OAuth 1.0) looks as follows:
public void AccessAPI ()
{
InMemoryOAuthTokenManager tokenManager = InMemoryOAuthTokenManager(YOUR_CLIENT_KEY, YOUR_CLIENT_SECRET);
var consumer = new DesktopConsumer(GetAuthServerDescription(), tokenManager);
// Get Request token
string requestToken;
var parameters = new Dictionary<string, string>();
parameters["email"] = "foo";
parameters["password"] = "bar";
Uri authorizationUrl = consumer.RequestUserAuthorization(null, parameters, out requestToken);
// Authorize and get a verifier (No OAuth Header necessary for the API I wanted to access)
var request = WebRequest.Create(authorizationUrl) as HttpWebRequest;
request.Method = "Get";
request.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
var response = request.GetResponse() as HttpWebResponse;
string verifier = new StreamReader(response.GetResponseStream()).ReadToEnd().Split('=')[1]; //Irgendwie will Json nicht parsen
// Use verifier to get the final AccessToken
AuthorizedTokenResponse authorizationResponse = consumer.ProcessUserAuthorization(requestToken, verifier);
string accessToken = authorizationResponse.AccessToken;
// Access Ressources
HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
var resourceEndpoint = new MessageReceivingEndpoint("https://api.discovergy.com/public/v1/meters", resourceHttpMethod);
using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken))
{
string result = resourceResponse.GetResponseReader().ReadToEnd();
dynamic content = JObject.Parse(result);
}
}
private ServiceProviderDescription GetAuthServerDescription()
{
var authServerDescription = new ServiceProviderDescription();
authServerDescription.RequestTokenEndpoint = new MessageReceivingEndpoint(YOUR_REQUEST_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
authServerDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(YOUR_AUTHORIZATION_ENDPOINT, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
authServerDescription.AccessTokenEndpoint = new MessageReceivingEndpoint(YOUR_TOKEN_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
authServerDescription.ProtocolVersion = ProtocolVersion.V10;
authServerDescription.TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
return authServerDescription;
}

Categories