My setup looks like this:
In my local envirenment I have an OPC server which reads data from local OPC devices and send them to my local little server which then sends the data to the IoT-Hub on Azure (and there I save the data to the cosmosDB).
The local little server which communicates to the IoT-Hub on Azure looks like this:
var connectionString = '[IoT Hub device connection string]';
// use factory function from AMQP-specific package
var clientFromConnectionString = require('azure-iot-device-amqp').clientFromConnectionString;
// AMQP-specific factory function returns Client object from core package
var client = clientFromConnectionString(connectionString);
// use Message object from core package
var Message = require('azure-iot-device').Message;
var connectCallback = function (err) {
if (err) {
console.error('Could not connect: ' + err);
} else {
console.log('Client connected');
var msg = new Message('some data from my device');
client.sendEvent(msg, function (err) {
if (err) {
console.log(err.toString());
} else {
console.log('Message sent');
};
});
};
};
client.open(connectCallback);
How Can I make sure that this communication is secure?
IoT Hub requires all connection to be secured via TLS (see IoT Hub MQTT Support ) and it only uses the secure version 1.2 (see IoT Hub TLS deprecating 1.0 and 1.1).
This will secure your transport (by default).
In production environment I would use X509 certificates to also secure identity and integrity.
To do so, please have a look at IoT Hub Security x509 Get Started to learn how to get and register certificates at IoT hub. And have a look at this Sample
which shows how to use X509 certificate in node.js code to connect to IoT hub.
Related
Request headers are passed on from the front end to the app service the middleware configured adds some additional headers to the request, but when this reaches the hub via (Azure Signal service) only the front end headers are available. The headers that was added in the middleware are lost? My StartUp.cs looks like below
services.AddSignalR(
hubOptions =>
{
hubOptions.EnableDetailedErrors = true;
})
.AddAzureSignalR(config =>
{
config.Endpoints = new[]
{
new ServiceEndpoint(new Uri(Configuration.GetValue<string>("SignalRServiceUrl")),
new ManagedIdentityCredential(Configuration.GetValue<string>("AZURE_CLIENT_ID")))
};
});
and below is for middleware and hub
app.UseMiddleware<AddHeaderMiddleware>();
app.UseAzureSignalR(endpoints =>
{
endpoints.MapHub<TestHub>("/api/TestHub");
});
Yes, all the header which you have set inside the web application middleware will missed. Only firstly negotiate will go to the server, then All the connection is make as the web-socket and client connect to the Azure Signlar Service not your application's hub.
If you enabled the Azure SignalR Server for your SignalR application. All the response which send from your SignalR application hub will firstly send to the Azure SignalR service and Azure SignalR service will return the response back to the client by using the web-socket.
I have developed an Azure Logic App with Http trigger in that I have used Service Bus Send Message action for posting messages to Azure Service Bus Queue.
I have configured the webhook with the Logic App endpoint in the third-party system. I’m getting the messages with Signing Key from third-party system. I want to validate the incoming message using Signing Key getting it from third-party system before posting messages to Azure Service Bus Queue through the Azure Logic App.
I have referred this documentation for validating the webhook message. But this documentation contains the explanation in .Net.
Is it Possible to validate/authenticate Signing Key in the Azure Logic App?
If you want to connect HMAC through Logic app you need to need to create a function app and call from function app so that you can use Signing Key for sending messages to Service Bus
Below is the sample function code where you can use this for generating a HMAC key
const CryptoJS = require("crypto-js");
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
//get the data used to sign from request body
const data = req.body.data
// sign
const str = CryptoJS.HmacSHA256(
CryptoJS.enc.Utf8.parse(req.body.data),,
"key"
);
const sig = CryptoJS.enc.Base64.stringify(str);
context.res = {
body: sig // return the hash
};
}
Now, you need to call Azure Function from Logic App to generate Key
Need to call API from Azure Function for that you can use hash data
Here is the expression to call has data #{body('<action name>')}
Also you need to call below values in headers in HTTP connector
Accept = Application/json
Accept = application/json
api-auth-id = (your function id)
api-auth-signature = #{body('getkey')}
Now you can execute your code to get your result. Also for further details you can check the below SO for related discussion.
I developed a flutter android app. and my database is MongoDB. I use Node.js API to connect my flutter app with the MongoDB. I want to send push notifications when a new data record is coming to MongoDB. How can I do that?
The simplest way is to use Firebase Cloud Messaging. Especially since Google is deprecating GCM which was previously used for Android. Also Firebase cloud messaging is free and can be used for both iOS and Android. Apple's APN service will require a setup as well though and a paid developer account.
Create a Firebase project if you haven't already and enable cloud messaging.
To set up your Node.js server so that it can send push notifications to your android and IOS devices. Click on the Project Overview, Settings and service accounts and follow the directions to generate a private key for your project and follow the instructions for setup. Also npm install "firebase-admin".
Once you have firebase setup refer to these docs for how to send messages. https://firebase.google.com/docs/cloud-messaging/send-message
There are several ways to send messages. You can send messages directly.
with this code
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
You can also create topics for devices to subscribe to as well if you are sending out mass notifications. More examples once again are within the docs. Now if you are wondering what the token is that is the next step.
The token comes from the unique device that is connecting to your platform. You can get the token by installing the Firebase Messaging sdk from https://pub.dev/packages/firebase_messaging and following the instructions to add the necessary dependencies to your pubsec.yaml and properly configure your Android manifest and iOS files for the changes.
This package will give you methods to grab your communicate and to receive the notifications that you have sent form your Node.JS server.
Here is an example of grabbing the token from your device on the frontend in flutter.
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
bool _initialized = false;
Future<void> init() async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(onMessage: (Map<String, dynamic> `enter code here`message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
At this point you would most likely save the token to your MongoDB database and associate the token with your user and that specific device. Of course you would have to also install the firebase core and for Flutter as well and do all of the necessary configurations.
You are still able to maintain your NodeJS API and MongoDB database and use free cloud messaging service to push your notifications for your server to your device.
We are using node.js' Mosca broker module for one of our applications. We are planning to add client authentication with a certificate on the broker side but I'm unable to find any configuration or settings in Mosca has for client authentication.
In the Mosquito broker configuration, the file has one property and requires that the certificate be true. Is there anything similar to that in Mosca?
According to the documentation, one can authenticate a client using
server.authenticate = function (client, username, password, callback) {
// To authenticate
callback(null, true);
// To reject
callback(null, false);
}
You can also override this function to be able to use certificate-based authentication or whatever else you wish.
I am developing a windows phone 8.1 App (RT), I am trying to push notification with Azure Notification Hub. I am able to do it with the client side SDK available. But I want to do the device registration, tagging etc. from the server side. I see a good guide for .Net backend at http://blogs.msdn.com/b/azuremobile/archive/2014/04/08/push-notifications-using-notification-hub-and-net-backend.aspx . I am using NodeJS in the backend server side. Can anyone help me in the same, with a sample code or so.
I want to register devices from server side (iPhone, Android & Windows Phone), actually I have the device tokens available at the servicer side which is sent from the device via API call.
I want to update multiple tags for each devices time to time.
I want to unregister the devices when user request to do so.
I want to send push notification to specific tags, using the template.
The steps to register the device token and sending out the notification using the Notification Hub in node.js are as follows:
Create a Registration ID
Create Registration
Send Notification
This is server side code, once the device token is received. Note that the registration ID, Device Token, Tag and Callback function are required parameters for notificationHubService.apns.send call.
Here is the code snippet:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<Hub Name>','<Connection String>');
var payload={
alert: 'Hello!'
};
notificationHubService.createRegistrationId(function(error, registrationId, response){
if(!error){
console.log(response);
console.log(registrationId);
//RegistrationDescription registration = null;
//registration.RegistrationId = registrationId;
//registration.DeviceToken = req.body.token;
notificationHubService.apns.createOrUpdateNativeRegistration(registrationId, req.body.token, req.token.upn, function(error, response){
if(!error){
console.log('Inside : createOrUpdateNativeRegistration' + response);
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
console.log('Success: Inside the notification send call to Hub.');
}
});
}
else{
console.log('Error in registering the device with Hub' + error);
}
});
}
else{
console.log('Error in generating the registration Id' + error);
}
});
Look at open source SDK for server side. I've never tried it out, but should be OK because any SDK is just a wrapper for REST API.