SingalR ASP.NET Cross Domain Connection Issue - asp.net

I am trying to implement an ASP.NET SignalR app as mentioned here.
I have implemented the client as mentioned here. For the client I am using code without the generated proxy.
Client and server successfully connect when both are on the same domain but unable to communicate when hosted cross domain. Although the code mentioned for cross domain in the above articles is already implemented. Since my client and server are hosted in Azure, is there a setting in Azure that needs to be enabled for cross domain communication or there is something else that I am missing?
Here is the error i am getting:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin is therefore not allowed access. The response had HTTP status code 500.
My startup class is:
public void Configuration(IAppBuilder app)
{
//app.UseCors(CorsOptions.AllowAll);
// Any connection or hub wire up and configuration should go here
//app.MapSignalR();
// Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
And the client code is:`
$(function (){
var ChatServerUrl ="http://chatserverurl.net/home/";
var ChatUrl = ChatServerUrl + "signalr";
var connection = $.hubConnection(ChatUrl, { useDefaultPath: false });
connection.logging = true;
var chatHubProxy = connection.createHubProxy('chatHub');
chatHubProxy.on('addNewMessageToPage', function (name, message) {
console.log("AddNewMessageToPage Function!");
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
});
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
//connection.start({ withCredentials : false }).done(function () {
connection.start({ withCredentials: true }).done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chatHubProxy.invoke('Send', $('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
console.log("SignalR Connected!");
});
});`

Please try this according to what the below links suggest
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

Related

can we unregister old service worker by its name and register new service worker

I am facing some problem related to service worker before some time i am using gcm and service worker file name was service-worker.js after releasing fcm i changed my code and now my service worker file name is firebase-messaging-sw.js but in some my client browser calling old service-worker.js file which is generating an error(service-worker.js not found 500). I already used following code before gettoken().
const messaging = firebase.messaging();
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
messaging.useServiceWorker(registration);
// Request permission and get token.....
});
but its still showing this error.
In general, if you have multiple service workers registered with different scopes, and you want to get a list of them from a client page (and potentially unregister some of them, based on either matching scope or SW URL), you can do the following:
async unregisterSWs({matchingScope, matchingUrl}) {
const registrations = await navigator.serviceWorker.getRegistrations();
const matchingRegistrations = registrations.filter(registration => {
if (matchingScope) {
return registration.scope === matchingScope;
}
if (matchingUrl) {
return registration.active.scriptURL === matchingUrl;
}
});
for (const registration of matchingRegistrations) {
await registration.unregister();
console.log('Unregistered ', registration);
}
}
and then call it passing in either a scope or SW script URL that you want to use to unregister:
unregisterSWs({matchingScope: 'https://example.com/push'});
unregisterSWs({matchingUrl: 'https://example.com/my-push-sw.js'});

Meteor patrickml:braintree Authentication Error

This command meteor add patrickml:braintree was run in a Meteor app directory.
In the client.main.js:
A squiggly line Under the variable braintree and the IDE says "unresolved variable or type".
Template.payment.onRendered(function () {
Meteor.call('getClientToken', function (error, clientToken) {
if (error) {
console.log(error); //<---- always prints out
} else {
//vvvvvvvvv
braintree.setup(clientToken, "dropin", {
container: "payment-form", // Injecting into <div id="payment-form"></div>
onPaymentMethodReceived: function (response) {
var nonce = response.nonce;
console.log(nonce);
}
});
}
});
});
In the server code below, clientId is always undefined.
//server/main.js
'getClientToken': function (clientId) {
console.log(clientId); //<--------- undefined
let generateToken = Meteor.wrapAsync(gateway.clientToken.generate, gateway.clientToken);
let options = {};
if (clientId) {
options.clientId = clientId;
}
let response = generateToken(options);
return response.clientToken;
}
And the server console prints out:
Exception while invoking method 'getClientToken' authenticationError: Authentication Error
Any idea what is wrong and how to fix it? thx
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
When you configure your gateway object, make sure that you use the API credentials documented in your Sandbox Control Panel. Here's how you can find them:
Log into the sandbox Control Panel
Navigate to Account > My user
Under API Keys, Tokenization Keys, Encryption Keys, click View Authorizations
If no API keys appear, click Generate New API Key
Click View under the Private Key column to see your public and private keys, merchant ID, and environment
When you have them, use them to configure your gateway object. For example:
var braintree = require("braintree");
var gateway = braintree.connect({
environment: braintree.Environment.Sandbox,
merchantId: "replaceWithYourMerchantId",
publicKey: "replaceWithYourPublicKey",
privateKey: "replaceWithYourPrivateKey"
});

app.post on parse heroku server is unauthorized

I am trying to post to my server from twilio, but I am getting a 403 error. Basically my parse-heroku serve is rejecting any request from twilio. I am working with TWIMLAPP and masked numbers. I am having trouble posting to a function in my index file when a text goes through. In my TWIMLAPP my message url is https://parseserver.herokuapp.com/parse/index/sms Any help is appreciated. These are the errors in twilio
var app = express();
app.use(require('body-parser').urlencoded());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://www.twilio.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader("X-Parse-Master-Key", "xxxxxxx");
res.setHeader("X-Parse-Application-Id", "xxxxxx");
// Pass to next layer of middleware
next();
});
app.post('/sms', twilio.webhook({ validate: false }), function (req, res) {
console.log("use-sms")
from = req.body.From;
to = req.body.To;
body = req.body.Body;
gatherOutgoingNumber(from, to)
.then(function (outgoingPhoneNumber) {
var twiml = new twilio.TwimlResponse();
twiml.message(body, { to: outgoingPhoneNumber });
res.type('text/xml');
res.send(twiml.toString());
});
});

Incorrect path to SignalR generated on client

So I have been plugging away trying to get SignalR to work with my Web Api instance that used OWIN and authentication. After figuring out CORS (thanks to SO help) I am almost there.
My web client fails with a Javascript error on the console.
http://localhost:45325/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22myhub%22%7D%5D&_=1460577212205 404 (Not Found)
if I take this URL and put it in the browser sure enough I get a 404 error. However if I add /signalr/ to the path as such ...
http://localhost:45325/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22myhub%22%7D%5D&_=1460577212205
I get a proper JSON response with the SignalR connectionid and everything ...
{
"Url": "/signalr",
"ConnectionToken": "<token here>",
"ConnectionId": "0bf84c7a-0a28-4da9-bb9f-551de894cf0e",
"KeepAliveTimeout": 20,
"DisconnectTimeout": 30,
"ConnectionTimeout": 110,
"TryWebSockets": true,
"ProtocolVersion": "1.5",
"TransportConnectTimeout": 5,
"LongPollDelay": 0
}
So it looks as though everything is working other than the fact that the URL the client is generating to connect to the SignalR hub is missing the /signalr.
Here is my client side Javascript that connects to the Hub. Where can I specify the path needs to include /signalr? Because I thought I already was ...
<script src="scripts/jquery-2.2.2.min.js"></script>
<script src="scripts/jquery.signalR-2.2.0.js"></script>
<script>
(function ($) {
$(function () {
var connection = $.hubConnection('/signalr/', {useDefaultPath: false});
var myHubProxy = connection.createHubProxy('MyHub');
myHubProxy.on('notify', function (username) {
console.log(username + ' has logged in');
alert(username + ' has logged in');
});
connection.url = 'http://localhost:45325';
connection.start()
.done(function() {
alert('Connected to MyHub: Connection ID = ' + connection.id);
})
.fail(function(e) {
console.log('Connection error: ' + e);
});
});
})(jQuery);
</script>
You may notice that I did not include <script src="signalr/hubs"></script>. This is because I am created the proxy myself instead of relying on the auto-generated proxy
I figured it out! It should have been obvious to me ...
In my Javascript on the client I needed to add the \signalr path ...
connection.url = 'http://localhost:45325/signalr';
Perhaps I should have seen that in my public void Configuration(IAppBuilder) method inside the Startup.cs class of my Web Api I had the following ..
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
// EnableJSONP = true; // I am not using as CORS is working just fine
};
map.RunSignalR(hubConfiguration);
});
I was specifying the subdirectory "/signalr"

How to listen to node http-proxy traffic?

I am using node-http-proxy. However, in addition to relaying HTTP requests, I also need to listen to the incoming and outgoing data.
Intercepting the response data is where I'm struggling. Node's ServerResponse object (and more generically the WritableStream interface) doesn't broadcast a 'data' event. http-proxy seems to create it's own internal request, which produces a ClientResponse object (which does broadcast the 'data' event) however this object is not exposed publically outside the proxy.
Any ideas how to solve this without monkey-patching node-http-proxy or creating a wrapper around the response object?
Related issue in issues of node-http-proxy on Github seems to imply this is not possible. For future attempts by others, here is how I hacked the issue:
you'll quickly find out that the proxy is only calling writeHead(), write() and end() methods of the res object
since res is already an EventEmitter, you can start emitting new custom events
listen for these new events to assemble the response data and then use it
var eventifyResponse = function(res) {
var methods = ['writeHead', 'write', 'end'];
methods.forEach(function(method){
var oldMethod = res[method]; // remember original method
res[method] = function() { // replace with a wrapper
oldMethod.apply(this, arguments); // call original method
arguments = Array.prototype.slice.call(arguments, 0);
arguments.unshift("method_" + method);
this.emit.apply(this, arguments); // broadcast the event
};
});
};
res = eventifyResponse(res), outputData = '';
res.on('method_writeHead', function(statusCode, headers) { saveHeaders(); });
res.on('method_write', function(data) { outputData += data; });
res.on('method_end', function(data) { use_data(outputData + data); });
proxy.proxyRequest(req, res, options)
This is a simple proxy server sniffing the traffic and writing it to console:
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});
// assign events
proxy.on('proxyRes', function (proxyRes, req, res) {
// collect response data
var proxyResData='';
proxyRes.on('data', function (chunk) {
proxyResData +=chunk;
});
proxyRes.on('end',function () {
var snifferData =
{
request:{
data:req.body,
headers:req.headers,
url:req.url,
method:req.method},
response:{
data:proxyResData,
headers:proxyRes.headers,
statusCode:proxyRes.statusCode}
};
console.log(snifferData);
});
// console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
// collect request data
req.body='';
req.on('data', function (chunk) {
req.body +=chunk;
});
req.on('end', function () {
});
});
proxy.on('error',
function(err)
{
console.error(err);
});
// run the proxy server
var server = http.createServer(function(req, res) {
// every time a request comes proxy it:
proxy.web(req, res, {
target: 'http://localhost:4444'
});
});
console.log("listening on port 5556")
server.listen(5556);
I tried your hack but it didn't work for me. My use case is simple: I want to log the in- and outgoing traffic from an Android app to our staging server which is secured by basic auth.
https://github.com/greim/hoxy/
was the solution for me. My node-http-proxy always returned 500 (while the direct request to stage did not). Maybe the authorization headers would not be forwarded correctly or whatever.
Hoxy worked fine right from the start.
npm install hoxy [-g]
hoxy --port=<local-port> --stage=<your stage host>:<port>
As rules for logging I specified:
request: $aurl.log()
request: #log-headers()
request: $method.log()
request: $request-body.log()
response: $url.log()
response: $status-code.log()
response: $response-body.log()
Beware, this prints any binary content.

Resources