I have a self-hosted WebAPI web service using a self-signed certificate. I am successfully able to communicate with the web service controller actions from other applications using the URL:
https://localhost:5150/...
Note that I have successfully bound the self-signed certificate to port 5150 and reserved the port for all IPs for my application, both by using the appropriate netsh commands.
I am trying to integrate a SignalR hub into this web service. I configure the hub, with CORS support, using the following in my startup code:
// Configure the SignalR hub that will talk to the browser
appBuilder.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
HubConfiguration hubConfig = new HubConfiguration();
hubConfig.EnableDetailedErrors = true;
hubConfig.EnableJavaScriptProxies = false;
map.RunSignalR(hubConfig);
});
I am starting up my HTTP listener, which is/was also used for Web API by this:
_webApp = WebApp.Start<Startup>(baseUrl);
where the baseUrl is
https://+:5150/.
My SignalR initialization code, in my Angular controller is:
var initialize = function () {
//Getting the connection object
connection = $.hubConnection("/signalr", { useDefaultPath: false });
// Url signalr scripts should hit back on the server
connection.url = ENV.SIGNALR.protocol + '://' + ENV.SIGNALR.server + ':' + ENV.SIGNALR.port + '/' + ENV.SIGNALR.url;
// Turn on client-side logging
connection.logging = ENV.SIGNALR.logging;
// Get proxy based on Hub name (must be camel-case)
proxy = connection.createHubProxy('dashboardHub');
// Setup event handlers for messages we get from the server.
proxy.on('rxDiagnosticMessage', function (msg) {
//console.log('Received rxDiagnosticMessage');
$rootScope.$broadcast("rx-diagnostic-message", msg);
});
//Starting connection
connection.start()
.done(function () { console.log('SignalR connection started'); })
.fail(function (err) { console.log('SignalR connection failed - ' + err); });
// Display errors to console
connection.error(function (err) {
console.log('SignalR error - ' + err);
});
};
When the connection to the hub is attempted, I get the following error:
15:04:43 GMT-0400 (Eastern Daylight Time)] SignalR: Auto detected cross domain url. jquery.signalR-2.1.0.js:81
[15:04:43 GMT-0400 (Eastern Daylight Time)] SignalR: Client subscribed to hub 'dashboardhub'. jquery.signalR-2.1.0.js:81
[15:04:43 GMT-0400 (Eastern Daylight Time)] SignalR: Negotiating with 'https://localhost:5150/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22dashboardhub%22%7D%5D'. jquery.signalR-2.1.0.js:81
GET https://localhost:5150/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22dashboardhub%22%7D%5D&_=1407524683014 net::ERR_INSECURE_RESPONSE jquery-2.1.1.js:8623
SignalR error - Error: Error during negotiation request. AppSignalR.js:43
SignalR connection failed - Error: Error during negotiation request. AppSignalR.js:39
[15:04:43 GMT-0400 (Eastern Daylight Time)] SignalR: Stopping connection.
Note the net::ERR_INSECURE_RESPONSE during the SignalR connection negotiation.
Strange thing...if I run Fiddler2 then the connection works! (Is Fiddler serving up a nice certificate to my web app / SignalR?)
I suspect this is due to the certificate being self-signed (cert in Personal, cert authority in Trusted). In WCF and WebAPI clients I always intercept the authority errors and bypass the error:
ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);
Is there something similar that needs to be done in the SignalR client in my Angular application? Or should this just work?
Note that I have seen this thread - SignalR with Self-Signed SSL and Self-Host still does not work for me.
You cannot use localhost with SSL, you need absolute HostName in URL.
Look at the ISSUED BY and ISSUED TO field in the Certificate you created, ISSUED BY needs to be part of the "Trusted Publisher" list on your machine(machine that is accessing the webpage using browser), and ISSUED TO needs to be part of your URL .i.e. the certificate has been issued to you and only you. So if your ISSUED TO field has value "HOSTNAME.DOMAINNAME" where HOSTNAMe is hostName of the machine and DomainName is the Domain of the machine where the web site is hosted, then you need to access your SITE using the same name i.e
.
Hope this helps.
Related
I'm trying to host a SignalR hub in a .NET Core 3.1 Windows Service, and when my client begins negotiation it fails with the response net::ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY
My SSL certificate is successfully loaded, and it checks out as valid in browser on port 443, but when browsing to my alternate port (randomly selected 12457) the browser does not consider it valid
If I switch down to HTTP1, I get a 405 I suspect from incompatibility with the client (microsoft/angular).
Here's how I'm configuring with my SSL certificate
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseUrls(configuration.GetValue<string>("ListenerEndpoint"));
webBuilder.UseKestrel(options =>
{
options.Listen(IPAddress.Any, 12457, listenOptions =>
{
listenOptions.UseHttps(options =>
{
var certificateStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine, OpenFlags.ReadOnly);
var certificates = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, "<thumbprint>", true);
var certificate = certificates[0];
options.ServerCertificate = certificate;
});
});
});
});
I've followed the netsh command to expose the cert on this port per: https://weblog.west-wind.com/posts/2013/Sep/23/Hosting-SignalR-under-SSLhttps#:~:text=Even%20if%20your%20self-hosted%20SignalR%20application%20doesn%27t%20explicitly,that%20will%20reject%20mixed%20content%20on%20SSL%20pages. without a positive effect
I am developing a web api and a web app locally. I am having trouble calling the web api from the web app.
When I call it I keep getting the error: "The remote certificate is invalid according to the validation procedure."
Both apps are built with ASP.Net Core and are running on kestrel. The webapp is callable as https://mylibrary.com:5003 and the Web API is callable as https://api.mylibrary.com:5001.
How can I get them working together with valid certificates?
Edit: Come to realise that the issue is that the apps are using localhost certs by default. I want to be able to use my own self signed cert.
If someone can point me to somewhere that explains how to set up two apps to use a self-signed certificate in .net core web projects please do :)
If you need to work around the cert validation using HttpClient, you could do it by creating a HttpClientHandler and passing it to HttpClient as per Rohit Jangid's answer to The SSL connection could not be established
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient client = new HttpClient(clientHandler)
Avoid accidentally circumventing certificate validation in production by checking if it is in development environment:
HttpClient httpClient = new HttpClient();
if (env.IsDevelopment())
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, ssl) => { return true; };
httpClient = new HttpClient(clientHandler);
}
Inject information about webhostenvironment by injecting it in the handler/action:
public async Task OnGet([FromServices] IWebHostEnvironment env)
Please try to use RestSharp library to make the webapi request and set the cert validation to true. see here
or you can install the dotnet dev certs by executing dotnet dev-certs https --trust in a command promt or powershell
Here is my paho client code
// Create a client instance
client = new Paho.MQTT.Client('127.0.0.1', 1883, "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
On Rabbitmq server everything is default seetings. When i run this code i get WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Connection closed before receiving a handshake response
What i am missing ?
From my personal experience with Paho MQTT JavaScript library and RabbitMQ broker on windows, here is a list of things that you need to do to be able to use MQTT from JS from within a browser:
Install rabbitmq_web_mqtt plugin (you may find latest binary here, copy it to "c:\Program Files\RabbitMQ Server\rabbitmq_server-3.6.2\plugins\", and enable from command line using "rabbitmq-plugins enable rabbitmq_web_mqtt".
Of course, MQTT plugin also needs to be enabled on broker
For me, client was not working with version 3.6.1 of RabbitMQ, while it works fine with version 3.6.2 (Windows)
Port to be used for connections is 15675, NOT 1883!
Make sure to specify all 4 parameters when making instance of Paho.MQTT.Client. In case when you omit one, you get websocket connection error which may be quite misleading.
Finally, here is a code snippet which I tested and works perfectly (just makes connection):
client = new Paho.MQTT.Client("localhost", 15675, "/ws", "client-1");
//set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
//connect the client
client.connect({
onSuccess : onConnect
});
//called when the client connects
function onConnect() {
console.log("Connected");
}
//called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
//called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
It's not clear in the question but I assume you are running the code above in a web browser.
This will be making a MQTT connection over Websockets (as shown in the error). This is different from a native MQTT over TCP connection.
The default pure MQTT port if 1883, Websocket support is likely to be on a different port.
You will need to configure RabbitMQ to accept MQTT over Websockets as well as pure MQTT, this pull request for RabbitMQ seams to talk about adding this capability. It mentions that this capability was only added in version 3.6.x and that the documentaion is still outstanding (as of 9th Feb 2016)
I have a WCF Cloud Service running in azure which I connect to from a .NET client. This is all working nicely and I have implemented security by enabling SSL (using a self signed certificate) and using active directory authorisation.
However, I have a number of scheduled jobs using the azure scheduler and these jobs call methods in the Cloud service but I am unable to setup the scheduled jobs as HTTPS jobs. They work fine as HTTP jobs but as soon as I change it to HTTPS I get the following error:
“Http Action - Request to host '.cloudapp.net' failed: TrustFailure The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”
I tried just accepting all certificates by adding the following code to the WCF web role’s OnStart method:
ServicePointManager.ServerCertificateValidationCallback
= delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
But the callback never gets invoked
So I assume I have to somehow add client certificate authentication to the scheduler job? But I cannot work out how.
I am creating the job through the Microsoft.WindowsAzure.Management.Scheduler Api e.g:
var action = new JobAction();
action.Type = JobActionType.Https;
action.Request = new JobHttpRequest();
action.Request.Method = "POST";
action.Request.Uri = new Uri(serviceURI);
action.Request.Body = soap;
action.RetryPolicy = new RetryPolicy()
{
RetryType = RetryType.None,
RetryCount = null
};
action.Request.Headers = new Dictionary<string, string>()
{
{ "Content-Type", "text/xml" },
{ "SOAPAction", "\"http://tempuri.org/" + serviceInterfaceName + "/" + methodName + "\"" }
};
var result = schedulerClient.Jobs.CreateOrUpdate(jobName, new JobCreateOrUpdateParameters()
{
action = action,
StartTime = startTime,
Recurrence = new JobRecurrence()
{
Frequency = frequency,
Interval = interval
}
});
and I see that in the JobAction class there is a property of the Request object called Authentication, I thought perhaps I might need to use that but I can find no documentation on how to use it?
Alternatively, I could create the schedule job through powershell or the azure portal interface if anyone can tell me how to successfully create an HTTPS schedule job through either of those methods?
Many thanks,
kelly
Scheduler jobs fail because it can't trust this endpoint. You need to use a trusted certificate for HTTPS calls from Scheduler.
Ok so i tried hosting the simplest oauth sample and the identity server both on iis, i have enable cors on the simplest oauth sample. So when i test the api using the javascript implicit client, on iis express it works flawlessly, it gets the token then when the token is sent the web api checks the token and authorizes the javascript client. the problem happens when i move the javascript imlicit client, the identity server, and the simple oath web api is hosted on iis, the javascript brings back the token correctly but when the token is sent to the web api it always return 401 unauthorized. So is there any configuration i have to add in order to run it on iis. i have made sure that anonymous authentication is the only enab;ed authentication mode. Any help or pointer is deeply appreciate.
I am trying to implement the samples given on iis. thanks for the help
I had the same issue. It was coming from my self signed certificate.
Try adding to your IdentityServerOptions
RequireSsl = false
and switch the WebApi Authority to use http.
Edit
Server Side Configuration
public void ConfigureIdentityServer(IAppBuilder app)
{
//Configure logging
LogProvider.SetCurrentLogProvider(new DiagnosticsTraceLogProvider());
//This is using a Factory Class that generates the client, user & scopes. Can be seen using the exmaples
var IdentityFactory = Factory.Configure("DefaultConnection");
app.Map("/identity", idsrvApp =>
{
idsrvApp.UseIdentityServer(new IdentityServerOptions
{
SiteName = "Security Proof of Concept",
SigningCertificate = LoadCertificate(),
Factory = IdentityFactory,
CorsPolicy = CorsPolicy.AllowAll,
RequireSsl = false
});
});
}
JavaScript
After receiving the token make sure it's inserted in the Authorization Header..
JQuery Example
$.ajax({
url: 'http://your.url',
type: GET,
beforeSend: function (xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", " Bearer " + apiToken);
}
});
WebApi Resource
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
//Location of identity server make full url & port
Authority = "http://localhost/identity",
RequiredScopes = new[] { "WebApiResource" }
//Determines if the Api Pings the Identity Server for validation or will decrypt token by it's self
//ValidationMode = ValidationMode.Local
});
Best way to determine what is happening is enable logging.