Skip to content

Instantly share code, notes, and snippets.

@danielpeintner
Last active November 2, 2022 07:46
Show Gist options
  • Save danielpeintner/09ac53fe43a694302cfb176e7de16f3e to your computer and use it in GitHub Desktop.
Save danielpeintner/09ac53fe43a694302cfb176e7de16f3e to your computer and use it in GitHub Desktop.
node-wot (basic authentication)
// example-client.js
Servient = require("@node-wot/core").Servient
HttpClientFactory = require("@node-wot/binding-http").HttpClientFactory
Helpers = require("@node-wot/core").Helpers
// create Servient and add HTTP binding
let servient = new Servient();
servient.addCredentials({
"urn:dev:wot:org:eclipse:thingweb:my-example-secure": {
username: "node-wot",
password: "hello"
}
});
servient.addClientFactory(new HttpClientFactory(null));
let wotHelper = new Helpers(servient);
wotHelper.fetch("http://localhost:8080/mycounter/").then(async (td) => {
try {
servient.start().then((WoT) => {
WoT.consume(td).then((thing) => {
// read a property "count" and print the value
thing.readProperty("count").then((s) => {
console.log(s);
});
});
});
} catch (err) {
console.error("Script error:", err);
}
}).catch((err) => { console.error("Fetch error:", err); });
// example-server-secure.js
Servient = require("@node-wot/core").Servient
HttpServer = require("@node-wot/binding-http").HttpServer
Helpers = require("@node-wot/core").Helpers
// create secure Servient with username & password credentials
let servient = new Servient();
servient.addCredentials({
"urn:dev:wot:org:eclipse:thingweb:my-example-secure": {
username: "node-wot",
password: "hello"
}
});
let httpConfig = {
security: {
scheme: "basic" // (username & password)
}};
// add HTTPS binding with configuration
servient.addServer(new HttpServer(httpConfig));
servient.start().then((WoT) => {
WoT.produce({
"@context": "https://www.w3.org/2019/wot/td/v1",
id: "urn:dev:wot:org:eclipse:thingweb:my-example-secure",
title: "MyCounter",
"securityDefinitions": {
"basic_sc": {"scheme": "basic", "in": "header"}
},
"security": "basic_sc",
properties: {
count: {
type: "integer"
}
}
}).then((thing) => {
console.log("Produced " + thing.getThingDescription().title);
thing.writeProperty("count", 0)
thing.expose().then(() => {
console.info(thing.getThingDescription().title + " ready");
console.info("TD : " + JSON.stringify(thing.getThingDescription()));
thing.readProperty("count").then((c) => {
console.log("cound is " + c);
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment