Security News
Node.js EOL Versions CVE Dubbed the "Worst CVE of the Year" by Security Experts
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
@azure-iot/authentication
Advanced tools
Provides Authentication support for Azure IOT microservices
This library provides support for user authentication in Azure IoT microservices.
1. Install Node
Node can be found here
2. npm install
This will download and install all dependencies required to build this script.
3. npm run build
This will build the project, putting the output into the src
folder.
This library provides the Authentication
module, which takes in an express
application and a few configuration values, and returns a middleware that the
application can use on routes to ensure the user is authenticated.
Internally, the library sets up an express session and a passport session, both
backed by mongodb, to ensure the req.user
object contains the authenticated
user information correctly when the route is executed.
This module does not actually authenticate against an OAuth providers directly: it merely sets up passport so the user is redirected to a specified login URL (typically hosted on a different service), which will then perform the authentication and redirect back to the page the user was originally trying to visit.
import {Authentication} from '@azure-iot/authentication';
const app = express();
const auth = await Authentication.initialize(
app, // an express application
'http://shell/login', // URL of the login page
'keyboard cat', // password to encrypt user sessions
'mongodb://localhost:27071'); // URI of the mongodb instance
app.get('/', auth.ensureAuthentication, (req, res) => res.sendStatus(200));
Authentication.initialize
initializes express and passport sessions backed by mongodb.http://localhost:3000/
) that specifies
auth.ensureAuthentication
as a middleware.http://localhost:3000/
) in the session, and redirects the
user to the login page (in our example, http://shell/login
)./login
route)
sees that the user is not authenticated, and redirects to the OAuth provider
(in our case, AAD) to actually authenticate the user.http://shell/auth/aad/return?code=foo&id_token=...
)User
entry in mongo (if one with the specified unique id
doesn't already exist), and gives it to Passport.req.user
property.This library will most likely be used only in a production environment, with the configuration fetched from the Config service. The following code demonstrates a helper module that a service can use to query the config service and initialize authentication with retry logic (for production environment, in case the config service hasn't been initialized yet), and fallback logic (for dev purposes, when the config needs to be fetched from a file instead of the config service.)
import * as express from 'express';
import * as request from 'request';
import {Authentication} from '@azure-iot/authentication';
export class Config {
constructor(
public IotHubConnectionString: string,
public EnsureAuthentication: express.RequestHandler) {}
public static async initialize(app: express.Express): Promise<Config> {
const waitForConfig = process.env.NODE_ENV === 'production';
const configUrl: string = process.env.CONFIG_URL || 'http://localhost:3009';
let result: Config = null;
do {
try {
const discovery = await getHal<void>(configUrl + '/api/discovery');
const settingsLink = discovery._links['settings:list'];
if (!settingsLink) throw new Error('Config service does not provide settings:list');
const configSettings = await getHal<ConfigSettings>(configUrl + settingsLink.href);
if (!configSettings.iotHubConnStr) throw new Error('Config service does not provide setting "iotHubConnStr"');
if (!configSettings.loginUrl) throw new Error('Config service does not provide setting "loginUrl"');
if (!configSettings.mongoUri) throw new Error('Config service does not provide setting "mongoUri"');
if (!configSettings.sessionSecret) throw new Error('Config service does not provide setting "sessionSecret"');
const auth = await Authentication.initialize(
app,
configSettings.loginUrl,
configSettings.sessionSecret,
configSettings.mongoUri);
return new Config(
configSettings.iotHubConnStr,
auth.ensureAuthenticated);
} catch (err) {
process.stderr.write(`WARNING: Could not initialize from Config Service: ${err}.\n`);
if (waitForConfig) {
// wait for 5 seconds before retrying:
await new Promise((resolve, reject) => setTimeout(resolve, 5000));
} else {
// we're in dev mode. Get config from file, and use empty
// middleware for authentication.
const userConfigFile = path.join(__dirname, '../user-config.json');
if (!fs.existsSync(userConfigFile)) {
console.log('Unable to find the user configuration: please fill out the information in ' + userConfigFile);
process.exit(1);
}
let userConfig: {
IotHubConnectionString: string;
} = require(userConfigFile);
return new Config(
userConfig.IotHubConnectionString,
(req, res, next) => next()); // empty middleware
}
}
} while (!result);
}
}
interface ConfigSettings {
iotHubConnStr: string;
loginUrl: string;
mongoUri: string;
sessionSecret: string;
'device-management': {
logLevel: string;
consoleReporting: string;
};
}
interface HalLink {
href: string;
}
interface HalResponse {
_links: {
self: HalLink;
[rel: string]: HalLink;
};
}
async function getHal<T>(uri: string) {
return new Promise<T & HalResponse>((resolve, reject) => {
request.get(uri, {json: true}, (err, response, body) => {
err ? reject(err) : resolve(body);
});
});
}
FAQs
Provides Authentication support for Azure IOT microservices
The npm package @azure-iot/authentication receives a total of 2 weekly downloads. As such, @azure-iot/authentication popularity was classified as not popular.
We found that @azure-iot/authentication demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 28 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.