Could not establish secure channel for SSL/TLS with authority in .net 5 - ssl

I am getting this error only with the application developed in .net 5.0,. For .net 4.5* application it is working fine.
With .net 5.0 console application when calling WCF service getting SSl/TLS issue. Already tried below code but not working:
ServicePointManager.ServerCertificateValidationCallback += ValidateServerCertficate;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
I have written this lines in Main function before creating the host:
Host.CreateDefaultBuilder(args)
Complete error is as below:
Could not establish trust relationship for the SSL/TLS secure channel with authority
Binding Used for WCF call is as below:
var binding = new BasicHttpsBinding
{
CloseTimeout = new TimeSpan(0, 1, 0),
OpenTimeout = new TimeSpan(0, 1, 0),
ReceiveTimeout = new TimeSpan(0, 1, 0),
SendTimeout = new TimeSpan(0, 1, 0),
MaxBufferPoolSize = 2147483647,
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647,
TransferMode = TransferMode.Buffered,
UseDefaultWebProxy = true,
AllowCookies = false,
MessageEncoding = WSMessageEncoding.Mtom,
Name = "dlBinding",
BypassProxyOnLocal = false,
Security =
{
Mode = BasicHttpsSecurityMode.TransportWithMessageCredential,
Transport = new HttpTransportSecurity
{
ClientCredentialType = HttpClientCredentialType.Certificate,
ProxyCredentialType = HttpProxyCredentialType.Basic,
}
}
};

Related

How to have an instance of CoreWCF.Channels.TransportBindingElement?

I have a legacy code written by .NET 4.7.2 which should be upgraded to netstandard2.0. Here is the legacy code:
TransportBindingElement bindingElement = new HttpsTransportBindingElement
{
RequireClientCertificate = true,
AllowCookies = false,
AuthenticationScheme = AuthenticationSchemes.Anonymous,
BypassProxyOnLocal = false,
DecompressionEnabled = true,
ExtendedProtectionPolicy = new ExtendedProtectionPolicy(
PolicyEnforcement.Always,
ProtectionScenario.TransportSelected,
null),
HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
KeepAliveEnabled = true,
ManualAddressing = false,
MaxBufferPoolSize = MaxBufferPoolSize,
MaxBufferSize = MaxBufferSize,
MaxReceivedMessageSize = MaxReceivedMessageSize,
MaxPendingAccepts = 0,
ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous,
TransferMode = TransferMode.Buffered,
UseDefaultWebProxy = true
};
Since the TransportBindingElement class is an abstract and HttpsTransportBindingElement is not defined in CoreWCF, the question is: what is the alternative solution for the above code to migrate to netstandard2.0 using CoreWCF?

cant consume queue from topic exchange rabbitmq

I have a weird issue with rabbit mq,my publisher service sends message to queue and i can see it there,in my consumer i cant get it even thought i go there with router key and exact queue name
var factory = new ConnectionFactory() { HostName = "myhst",
UserName = "payoutservice",
Password = pass};
using (var connection = factory.CreateConnection())
using ( _channel = connection.CreateModel())
{
_channel.ExchangeDeclare("payin-exchange", ExchangeType.Topic);
_channel.QueueDeclare("OpenPaymentReceiveResponseQueue", durable: true, exclusive: false, autoDelete: false, arguments: null);
_channel.QueueBind(queue: "OpenPaymentReceiveResponseQueue",
exchange: "payin-exchange",
routingKey: "payin");
//}
Console.WriteLine(" [*] Waiting for messages. To exit press CTRL+C");
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
var routingKey = ea.RoutingKey;
};
in the last part doesn't go inside consumer.Received and does not even hit my breakpoint inside there
Have you included an explicit call to for the consumer to consume from the queue? E.g.,
channel.BasicConsume(queue: queueName,
autoAck: true,
consumer: consumer);
There are helpful examples that you can look over here: https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html

SecurityTokenSignatureKeyNotFoundException in OWIN OpenID Connect middleware connecting to Google

We are using the generic OpenID Connect middleware to use Google as an external identity provider using IdentityServer3. We don't have MetadataAddress or any special TokenValidationParameters set up (so it should be getting the metadata based on Authority, and then filling in parameters based on that, which should be fine). We are getting the following error highly intermittently. Other questions I've come up with that have this error seem to involve incorrect custom validation and are not intermittent.
Authentication Failed : Microsoft.IdentityModel.Protocols.OpenIdConnectMessage : System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException : IDX10500 : Signature validation failed.Unable to resolve SecurityKeyIdentifier : 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 1,
Clause[0] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
)
',
token : '{"alg":"RS256","kid":"74e0db263dbc69ac75d8bf0853a15d05e04be1a2"}.{"iss":"https://accounts.google.com","iat":1484922455,"exp":1484926055, <snip more claims>}'.
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)in c : \ workspace \ WilsonForDotNet45Release \ src \ System.IdentityModel.Tokens.Jwt \ JwtSecurityTokenHandler.cs : line 943
at System.IdentityModel.Tokens.JwtSecurityTokenHandler.ValidateToken(String securityToken, TokenValidationParameters validationParameters, SecurityToken & validatedToken)in c : \ workspace \ WilsonForDotNet45Release \ src \ System.IdentityModel.Tokens.Jwt \ JwtSecurityTokenHandler.cs : line 671
at Microsoft.IdentityModel.Extensions.SecurityTokenHandlerCollectionExtensions.ValidateToken(SecurityTokenHandlerCollection tokenHandlers, String securityToken, TokenValidationParameters validationParameters, SecurityToken & validatedToken)in c : \ workspace \ WilsonForDotNet45Release \ src \ Microsoft.IdentityModel.Protocol.Extensions \ SecurityTokenHandlerCollectionExtensions.cs : line 71
at Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationHandler. < AuthenticateCoreAsync > d__1a.MoveNext()
The kid referred to is presently the 2nd of 3 keys at https://www.googleapis.com/oauth2/v3/certs.
Our Options look like this:
var options = new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "Google",
Caption = "Sign in with Google",
Scope = "openid email profile",
ClientId = clientId,
Authority = "https://accounts.google.com/",
AuthenticationMode = AuthenticationMode.Passive,
RedirectUri = new Uri(baseUri, "identity/signin-google").ToString(),
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = context => HandleException(context),
RedirectToIdentityProvider = context => AddLoginHint(context),
},
SignInAsAuthenticationType = signInAsType
};
app.UseOpenIdConnectAuthentication(options);
Is this a configuration issue or some sort of transient error that needs to be dealt with (and if so how)? The end client is doing one retry (though I don't think it's waiting at all) but that doesn't seem to help.
The problem here seems to have been caused by the fact that the default ConfigurationManager caches results for 5 days, while Google rolls over their keys much more frequently (more like daily). With the default behavior of the OWIN middleware, the first request with an unrecognized key will fail, and then on the next request it will refresh the keys.
The solution is to pass in your own ConfigurationManager with a faster AutomaticRefreshInterval. Most of the settings below are as in OpenIdConnectAuthenticationMiddleware
private static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
{
var baseUri = new Uri("https://localhost:44333");
var googleAuthority = "https://accounts.google.com/";
var metadataAddress = googleAuthority + ".well-known/openid-configuration";
var httpClient = new HttpClient(new WebRequestHandler());
httpClient.Timeout = TimeSpan.FromMinutes(1);
httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
var configMgr = new ConfigurationManager<OpenIdConnectConfiguration>(metadataAddress, httpClient)
{
// Default is 5 days, while Google is updating keys daily
AutomaticRefreshInterval
=
TimeSpan
.FromHours(12)
};
var options = new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "Google",
Caption = "Google",
Scope = "openid email profile",
ClientId = GoogleClientId,
Authority = googleAuthority,
ConfigurationManager = configMgr,
AuthenticationMode = AuthenticationMode.Passive,
RedirectUri =
new Uri(baseUri, "identity/signin-google").ToString(),
SignInAsAuthenticationType = signInAsType
};
app.UseOpenIdConnectAuthentication(options);
}

Dynamics CRM Web Api Function: Illegal characters in path when using encodeURIComponent

I'm trying to use the Search Function (https://msdn.microsoft.com/en-us/library/mt608029.aspx) via the Dynamics CRM 2016 Web API. This is my code:
var start = new Date(2016, 2, 1, 17, 0, 0);
var end = new Date(2016, 2, 10, 18, 0, 0);
var request = new Object();
request.AppointmentRequest = new Object();
request.AppointmentRequest.SearchWindowStart = start.toISOString();
request.AppointmentRequest.SearchWindowEnd = end.toISOString();
request.AppointmentRequest.ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44";
request.AppointmentRequest.Direction = 0;
request.AppointmentRequest.NumberOfResults = 10;
request.AppointmentRequest.UserTimeZone = 1;
var req = new XMLHttpRequest()
req.open("GET", clientUrl + "/api/data/v8.0/Search(" + encodeURIComponent( JSON.stringify(request) ) +")", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
alert(req.responseText);
}
else {
alert(req.response);
}
};
req.send();
When I initially tried this using CRM Online I received the following error:
"An error has occurred.
Try this action again. If the problem continues, check the Microsoft Dynamics >CRM Community for solutions or contact your organization's Microsoft >Dynamics CRM Administrator. Finally, you can contact Microsoft Support."
When I try this with an On-Premise deployment with DevErrors="On" in the web.config, I see the following error in the Event Viewer:
Exception information:
Exception type: HttpException
Exception message: A potentially dangerous Request.Path value was detected >from the client (:).
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext >context)
Request information:
Request URL: http://win-0e5dfqgqorm:444/ORG/api/data/v8.0/Search({"AppointmentRequest":{"SearchWindowStart":"2016-03-01T17:00:00.000Z","SearchWindowEnd":"2016-03-10T18:00:00.000Z","ServiceId":"5f3b6e7f-48c0-e511-80d7-d89d67631c44","Direction":0,"NumberOfResults":10,"UserTimeZone":1}})
Request path: /SHUDEV/api/data/v8.0/Search({"AppointmentRequest":{"SearchWindowStart":"2016-03-01T17:00:00.000Z","SearchWindowEnd":"2016-03-10T18:00:00.000Z","ServiceId":"5f3b6e7f-48c0-e511-80d7-d89d67631c44","Direction":0,"NumberOfResults":10,"UserTimeZone":1}})
The JSON object is encoded so I'm not sure why it's detected illegal characters. The SDK documentation for the Web Api is light and doesn't go into too much detail as to how to pass a ComplexType to a Web Api function, has anyone seen this issue before/managed to pass a ComplexType to a Web Api function?
Thanks in advance.
I managed to resolve this issue. The key is to pass the JSON object in as a query parameter:
var request = new Object();
request.SearchWindowStart = start.toISOString();
request.SearchWindowEnd = end.toISOString();
request.ServiceId = "5f3b6e7f-48c0-e511-80d7-d89d67631c44";
request.Direction = '0';
request.NumberOfResults = 10;
request.UserTimeZoneCode = 1;
var req = new XMLHttpRequest()
req.open("GET", clientUrl + "/api/data/v8.0/Search(AppointmentRequest=#request)?#request=" + JSON.stringify(request) , true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
alert(req.responseText);
}
else {
alert(req.response);
}
};
req.send();
This is documented in the SDK: https://msdn.microsoft.com/en-us/library/gg309638.aspx.
Hope this helps anyone who runs into a similar issue.

Using Windows Authenticated WCF services

I have a Windows authenticated WCF service.
Using the following configuration:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
binding.SendTimeout = TimeSpan.FromMinutes(60);
binding.CloseTimeout = TimeSpan.FromMinutes(60);
binding.OpenTimeout = TimeSpan.FromMinutes(60);
binding.ReceiveTimeout = TimeSpan.FromMinutes(60);
NexumCrmServiceClient client = new NexumCrmServiceClient(binding, new EndpointAddress("http://xxxxxx:81/xxxxxxxxxxxxxx.svc"));
client.ClientCredentials.Windows.AllowNtlm = true;
//client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("xxxxxxxx", "xxxxxxxx", "xxxxxxxxx");
I'm getting this error:
There was no endpoint listening at
http://xxxxxx:81/xxxxxxxxxxxxxxxx.svc that could accept the message.
This is often caused by an incorrect address or SOAP action. See
InnerException, if present, for more details...
And if I use the configuration below:
BasicHttpBinding binding = new BasicHttpBinding();
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.SendTimeout = TimeSpan.FromMinutes(60);
binding.CloseTimeout = TimeSpan.FromMinutes(60);
binding.OpenTimeout = TimeSpan.FromMinutes(60);
binding.ReceiveTimeout = TimeSpan.FromMinutes(60);
NexumCrmServiceClient client = new NexumCrmServiceClient(binding, new EndpointAddress("http://xxxxxx:81/xxxxxxxxxxxxxx.svc"));
client.ClientCredentials.Windows.AllowNtlm = true;
//client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("xxxxxxxx", "xxxxxxxx", "xxxxxxxxx");
I'm getting another error:
The HTTP request is unauthorized with client authentication scheme
'Anonymous'. The authentication header received from the server was
'Negotiate,NTLM'.
Would you please suggest a configuration that works successfully?
Thanks in advance,
I believe you need to set:
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows
to get what your question title is referring to. Also, review this MSDN article on using Windows authentication with basicHttpBinding.