Search code examples
javascript.netwebsocketsignalrcontent-security-policy

SignalR Refused to connect to [url] because it violates the following Content Security Policy directive


I've created a SignalR project in .NET 4.8.

I was using signalR correctly as described in the documentation. My two script tags:

<script src="~/Scripts/jquery.signalR-2.4.1.js"></script>
<script src="https://mySignalRServer/signalr/hubs"></script>

I'm initializing the connection in the following way:

$.connection.hub.url = "https://mySignalRServer/signalr";
let screencasting = $.connection.screencastingHub;

$.connection.hub.qs = 'uuid=' + masterGuid + '&master=true';
$.connection.hub.logging = true;
screencasting.client.changeTransport = changeTransport;

$.connection.hub.start({ transport: 'webSockets' }).done(function () {
    console.log('---Connected to signalR server via WebSockets');
});

When the code hits the following line $.connection.hub.start() the following error occurs:

enter image description here

jquery.signalR-2.4.1.js:1871 Refused to connect to 'wss://mySignalRServer/signalr/connect?transport=webSockets&clientProtocol=2.1&uuid=56b12321-1091-48aa-b52f-dc1407b3804a&master=true&connectionToken=WOP95HhCwdN7ogruYHpfrrsZofenOqo5kRDVLJh6S6zUH0AN74cUTEL44qORGBCRMWiGH5ei12826qLB%2BMHFa7YqaN1KeIYmG7dUaE%2B6DiF2CIwaNTl4dwbwR6t3Cxgx&connectionData=%5B%7B%22name%22%3A%22screencastinghub%22%7D%5D&tid=8' because it violates the following Content Security Policy directive: "connect-src https:".

Interestingly enough, this code was working fine. Could it be a sertificate error? How can I add this Content Security Policy (CSP). (enter link description here)

Is it added as header somewhere? In the html head?


Solution

  • After a lot of tests, this is the solution that worked out for me:

    In Web.config file I've added the following line:

    <httpProtocol>
          <customHeaders>
            <add name="Content-Security-Policy" value="default-src https:; connect-src https: wss:" />
          </customHeaders>
    </<httpProtocol>
    

    For more information, check this and that out.