How to use WebProxy with RestSharp? - restsharp

I would like to know how to use WebProxy with RestSharp. I am using version 108.0.1 and the code given below returns 407 when running locally from my workstation, which should use my credentials.
var client = new RestClient("https://www.google.com");
var proxy = new System.Net.WebProxy("http://mycorpproxy.com");
proxy.UseDefaultCredentials = true;
client.Options.Proxy = proxy;
var request = new RestRequest();
request.Method = Method.Get;
var response = client.Execute(request);

You need to specify the proxy in the options when you create the client, not after. In v107, the options object properties were init-only, but it fails on legacy SDKs, so we had to revert it to setters, but setting the options that are used to create an HttpClient instance after the client is created has no effect.
var proxy = new WebProxy("http://mycorpproxy.com") {
UseDefaultCredentials = true
};
var options = new RestClientOptions("https://www.google.com") {
Proxy = proxy
};
var client = new RestClient(options);

Related

Apache Commons HttpClient with user authentication

Need to do an HTTP GET with user ID and password authentication using the Apache Commons HttpClient:
val targetHost = new HttpHost("url", 8080, "http");
val credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));
val authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());
val context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
val client = HttpClientBuilder.create().build();
var response = client.execute(new HttpGet("url"), context);
var statusCode = response.getStatusLine().getStatusCode();
But it's not able to fetch the data from the URL as it is failing to connect to the URL. Can someone assist?
Check the parameters to HTTPHost. I'm pretty sure that you don't intend to connect to a server named url.

How to attach client certificate to AspNetCore TestServer api?

I'm looking at Microsoft.AspNetCore.TestHost.TestServer in the Microsoft source code. There I see the CreateClient() property that is HttpClient objects.
So how do I attached the client certificate for Digitial Signature in xUnit Test?
HttpClient example would be this.
var x509Certificate2 = new X509Certificate(); // Pretend it contains certificate data already.
var httpClientHandler = new HttpClientHandler() {
ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(x509Certificate2);
using (var httpClient = new HttpClient(httpClientHandler))
{
}
Now using the TestServer
var testServer = new TestServer();
testServer.CreateClient(); // How do I attached client certificate here?
So, how do we attach the client certificate here? For CreateClient()
Also, I can try to make do with implementing the HttpRequestMessage but it doesn't support that certificate option either.
You may try to use the testServer.SendAsync(...) method and just construct your HttpContext from there.
var result = await server.SendAsync(context =>
{
context.Connection.ClientCertificate = myClientCertificate;
context.Request.Method = "POST";
});
Just make sure to specify the Path and the Body as needed.

WSE2 to WCF: Signing a SOAP message

I need to covert code from WSE2 to WCF and need a few tips on how to implement signing a SOAP message with a X509Certificate2 object.
WSE2 code:
X509SecurityToken tok = new X509SecurityToken(cert);
SoapContext cont = cfs.RequestSoapContext;
cont.Security.Tokens.Add(tok);
cont.Security.Elements.Add(new MessageSignature(tok));
"cert" is my X509Certificate2 object and "cfs" is my Web Services client object.
How can I make this work without WSE2, how to do the same in WCF?
You can use a custom binding for that, but first you must figure out which kind of binding you need. Look here and here. On custom binding you can add security token for signing. My asymmetric binding looks like this: (but you can also use symmetric binding)
AsymmetricSecurityBindingElement asymmetricBinding = SecurityBindingElement.CreateMutualCertificateDuplexBindingElement(
MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
asymmetricBinding.InitiatorTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient
};
asymmetricBinding.RecipientTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.Never
};
asymmetricBinding.EndpointSupportingTokenParameters.SignedEncrypted.Add(new UserNameSecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient
});
asymmetricBinding.IncludeTimestamp = true;
asymmetricBinding.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
asymmetricBinding.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
var textMessageEncoding = new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
var httpsTransport = new HttpsTransportBindingElement();
CustomBinding b = new CustomBinding(asymmetricBinding, textMessageEncoding, httpsTransport);
Then you can set certificates on ClientCredentials of the EndpointClient
var wsClient = new YourEndpointClient(b, new EndpointAddress(yourWsEndPointAddress));
wsClient.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(cert);
wsClient.ClientCredentials.ServiceCertificate.DefaultCertificate = new X509Certificate2(cert);

OAuth2 grant_type missing

I am getting error that required parameter grant_type is missing in the request.
Using OAuth2 for Webserver application.
Please see below the code:
var httpClient : HTTPClient = new HTTPClient();
httpClient.setTimeout(3500);
httpClient.setRequestHeader("ContentType", "application/x-www-form-urlencoded");
httpClient.open("POST", "https://accounts.google.com/o/oauth2/token");
var param1:String = "code="+Encoding.toURI(pdict.CurrentHttpParameterMap.code.value.split('.')[0]);
var param2:String = "client_id="+pdict.session.custom.client_id;
var param3:String = "client_secret="+pdict.session.custom.client_secret;
var param4:String = "redirect_uri="+Encoding.toURI(pdict.session.custom.redirect_uri);
var param5:String = "scope=";
var param6:String = "grant_type=authorization_code";
Using below syntax i.e. passing variables as part of Request body solved it.
var client_secret : HTTPRequestPart = new HTTPRequestPart("client_secret", pdict.session.custom.client_secret);

How do configure username/password authentication for WCF netTcpBinding?

I would like to be able to use username/password authentication with nettcpbinding, is that possible? (UserNamePasswordValidator or something like that), no windows authentication.
I'm configuring everything with code, so please only use code and not app.config in any examples.
This is what I came up with, I have no idea if some of the code is not required:
Service host:
ServiceHost host = new ServiceHost(concreteType);
var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true);
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
host.AddServiceEndpoint(serviceType, binding, "net.tcp://someaddress:9000/" + name);
host.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator();
host.Credentials.ServiceCertificate.Certificate = new X509Certificate2("mycertificate.p12", "password");
host.Credentials.UserNameAuthentication.UserNamePasswordValidationMode =
UserNamePasswordValidationMode.Custom;
And client side:
var binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential, true);
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
var factory = new ChannelFactory<ISwitchService>(binding,
new EndpointAddress(
new Uri("net.tcp://someaddress:9000/switch")));
factory.Credentials.UserName.UserName = "myUserName";
factory.Credentials.UserName.Password = "myPassword";