SlideShare a Scribd company logo
Shubhra Kar | Products & Education
twitter:@shubhrakar
{“Node.js”: “APIs @hyperscale”}
SSL – Setup in Loopback.io
$ openssl genrsa -out privatekey.pem 1024
$ openssl req -new -key privatekey.pem -out certrequest.csr
$ openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out
certificate.pem
var path = require('path'),
fs = require("fs");
exports.privateKey = fs.readFileSync(path.join(__dirname,
'./private/privatekey.pem')).toString();
exports.certificate = fs.readFileSync(path.join(__dirname,
'./private/certificate.pem')).toString();
SSL – App Usage in Loopback.io
var https = require('https');
var sslConfig = require('./ssl-config');
...
var options = {
key: sslConfig.privateKey,
cert: sslConfig.certificate
};
…
server.listen(app.get('port'), function() {
var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' +
app.get('port');
app.emit('started', baseUrl);
console.log('LoopBack server listening @ %s%s', baseUrl, '/');
});
return server;
ACL in Loopback.io
READ:
exists - Boolean method that determines whether a user exists.
findById - Find a user by ID.
find - Find all users that match specified conditions.
findOne - Finds a single user instance that matches specified
conditions.
count - Returns the number of users that match the specified
conditions.
WRITE:
create - create a new user.
updateAttributes (update) - update a user record.
upsert (update or insert) - update or insert a new user record.
destroyById (equivalent to removeById or deleteById) - delete the user
with the specified ID.
For other methods, the default access type is EXECUTE; for example, a
custom method maps to the EXECUTE access type.
Full Stack (MEAN App Angular frontend)
Full Stack (Loopback backend API)
Full Stack (Loopback backend API Authorization)
Static Roles in Loopback.io
User.create([
{username: 'John', email: 'john@doe.com', password: 'opensesame'},
{username: 'Jane', email: 'jane@doe.com', password: 'opensesame'},
{username: 'Bob', email: 'bob@projects.com', password: 'opensesame'}
], function(err, users) {
if (err) return cb(err);
//create the admin role
Role.create({
name: 'admin'
}, function(err, role) {
if (err) cb(err);
//make bob an admin
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[2].id
}, function(err, principal) {
cb(err);
});
});
});
Mapping Roles to ACLs
{
"accessType": "EXECUTE",
"principalType": "ROLE",
"principalId": "admin",
"permission": "ALLOW",
"property": "find"
}
Built in dynamic roles in Loopback.io
Built in dynamic roles in Loopback.io
module.exports = function(app) {
var Role = app.models.Role;
Role.registerResolver('teamMember', function(role, context, cb) {
function reject(err) {
if(err) {
return cb(err);
}
cb(null, false);
}
if (context.modelName !== 'project') {
// the target model is not project
return reject();
}
var userId = context.accessToken.userId;
if (!userId) {
return reject(); // do not allow anonymous users
}
Built in dynamic roles in Loopback.io
// check if userId is in team table for the given project id
context.model.findById(context.modelId, function(err, project) {
if(err || !project) {
reject(err);
}
var Team = app.models.Team;
Team.count({
ownerId: project.ownerId,
memberId: userId
}, function(err, count) {
if (err) {
return reject(err);
}
cb(null, count > 0); // true = is a team member
});
});
});
};
Mapping Dynamic Role to ACLs.
{
"accessType": "READ",
"principalType": "ROLE",
"principalId": "teamMember",
"permission": "ALLOW",
"property": "findById"
}
OAuth2.0 and JWT in Loopback.io
Setup – OAuth 2.0 in Loopback.io
npm install loopback-component-oauth2
Configuration – OAuth2.0 in Loopback.io
var oauth2 = require('loopback-component-oauth2');
var options = {
dataSource: app.dataSources.db, // Data source for oAuth2 metadata
persistence
loginPage: '/login', // The login page URL
loginPath: '/login' // The login form processing URL
};
oauth2.oAuth2Provider(
app, // The app instance
options // The options
);
oauth2.authenticate(['/protected', '/api', '/me'],
{session: false, scope: 'email'})
Authenticating and Securing Node.js APIs
3rd Party Logins using Passport strategies
Setup of passport component in Loopback.io
npm install loopback-component-passport
Config – Facebook Authentication in Loopback.io
{
"facebook-login": {
"provider": "facebook",
"module": "passport-facebook",
"clientID": "{facebook-client-id-1}",
"clientSecret": "{facebook-client-secret-1}",
"callbackURL": "http://localhost:3000/auth/facebook
/callback",
"authPath": "/auth/facebook",
"callbackPath": "/auth/facebook/callback",
"successRedirect": "/auth/account",
"scope": ["email"]
}
Config – Google Authentication in Loopback.io
{
"google-link": {
"provider": "google",
"module": "passport-google-oauth",
"strategy": "OAuth2Strategy",
"clientID": "{google-client-id-2}",
"clientSecret": "{google-client-secret-2}",
"callbackURL": "http://localhost:3000/link/google/
callback",
"authPath": "/link/google",
"callbackPath": "/link/google/callback",
"successRedirect": "/link/account",
"scope": ["email", "profile"],
"link": true
}
Config – MS AD Authentication in Loopback.io
{
"ms-ad": {
"provider": "ms-ad",
"authScheme":"ldap",
"module": "passport-ldapauth",
"authPath": "/auth/msad",
"successRedirect": "/auth/account",
"failureRedirect": "/msad",
"failureFlash": true,
"session": true,
"LdapAttributeForLogin": "mail",
"LdapAttributeForUsername": "mail",
"LdapAttributeForMail": "mail",
"server":{
"url": "ldap://ldap.example.org:389/dc=example,dc=org",
"bindDn": "bindUsername",
"bindCredentials": "bindPassword",
"searchBase": "ou=people,dc=example,dc=org",
"searchAttributes": ["cn", "mail", "uid", "givenname"],
"searchFilter": "(&(objectcategory=person)(objectclass=user)(|(s
amaccountname={{username}})(mail={{username}})))"
}
}
Application Level passport configurator in Loopback
// Create an instance of PassportConfigurator with the app instance
var PassportConfigurator = require('loopback-component-
passport').PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);
app.boot(__dirname);
...
// Enable http session
app.use(loopback.session({ secret: 'keyboard cat' }));
// Load the provider configurations
var config = {};
try {
config = require('./providers.json');
} catch(err) {
console.error('Please configure your passport strategy in `providers.json`.');
console.error('Copy `providers.json.template` to `providers.json` and
replace the clientID/clientSecret values with your own.');
process.exit(1);
}
Application Level using Passport configurator
// Initialize passport
passportConfigurator.init();
// Set up related models
passportConfigurator.setupModels({
userModel: app.models.user,
userIdentityModel: app.models.userIdentity,
userCredentialModel: app.models.userCredential
});
// Configure passport strategies for third party auth providers
for(var s in config) {
var c = config[s];
c.session = c.session !== false;
passportConfigurator.configureProvider(s, c);
}
Synchronous API “Re-Composition” is an anti-pattern
Security & Social Logins
Loopback async API Gateway*
Authenticating and Securing Node.js APIs
Micro services scaling
Hyper-scale & Micro-services Deployment

More Related Content

PDF
StrongLoop Node.js API Security & Customization
PDF
Loopback presentation by tineco
PPTX
Working with LoopBack Models
PDF
Picking the Right Node.js Framework for Your Use Case
ODP
Codegnitorppt
KEY
An Introduction to webOS
PDF
Microservices with Spring Boot
PDF
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...
StrongLoop Node.js API Security & Customization
Loopback presentation by tineco
Working with LoopBack Models
Picking the Right Node.js Framework for Your Use Case
Codegnitorppt
An Introduction to webOS
Microservices with Spring Boot
Java Web Application Security with Java EE, Spring Security and Apache Shiro ...

What's hot (20)

PDF
Modular Test-driven SPAs with Spring and AngularJS
PDF
Serverless - Developers.IO 2019
PPTX
Apex & jQuery Mobile
PDF
Do you want a SDK with that API? (Nordic APIS April 2014)
PDF
Building Progressive Web Apps for Android and iOS
PDF
Angular vs React for Web Application Development
PDF
Local Authentication par Pierre-Alban Toth
PPTX
Javascript first-class citizenery
PDF
Progressive Web Apps
PPT
You Know WebOS
PDF
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
KEY
【前端Mvc】之豆瓣说实践
PDF
Angular JS blog tutorial
PDF
Google Cloud Endpointsによる API構築
PDF
Chrome enchanted 2015
PDF
Instant and offline apps with Service Worker
KEY
Mobile HTML, CSS, and JavaScript
PPT
Managing JavaScript Dependencies With RequireJS
PPTX
Plugins unplugged
Modular Test-driven SPAs with Spring and AngularJS
Serverless - Developers.IO 2019
Apex & jQuery Mobile
Do you want a SDK with that API? (Nordic APIS April 2014)
Building Progressive Web Apps for Android and iOS
Angular vs React for Web Application Development
Local Authentication par Pierre-Alban Toth
Javascript first-class citizenery
Progressive Web Apps
You Know WebOS
Single Page Web Apps As WordPress Admin Interfaces Using AngularJS & The Word...
【前端Mvc】之豆瓣说实践
Angular JS blog tutorial
Google Cloud Endpointsによる API構築
Chrome enchanted 2015
Instant and offline apps with Service Worker
Mobile HTML, CSS, and JavaScript
Managing JavaScript Dependencies With RequireJS
Plugins unplugged
Ad

Viewers also liked (10)

PPTX
Building a Node.js API backend with LoopBack in 5 Minutes
PDF
Gotta Persist 'Em All: Realm as Replacement for SQLite
PDF
Rapid API Development with LoopBack/StrongLoop
PPTX
PDF
LoopBack: a productivity booster for MEAN
PDF
Node.js Frameworks & Design Patterns Webinar
PDF
Toronto node js_meetup
PDF
2015 Upload Campaigns Calendar - SlideShare
PPTX
What to Upload to SlideShare
PDF
Getting Started With SlideShare
Building a Node.js API backend with LoopBack in 5 Minutes
Gotta Persist 'Em All: Realm as Replacement for SQLite
Rapid API Development with LoopBack/StrongLoop
LoopBack: a productivity booster for MEAN
Node.js Frameworks & Design Patterns Webinar
Toronto node js_meetup
2015 Upload Campaigns Calendar - SlideShare
What to Upload to SlideShare
Getting Started With SlideShare
Ad

Similar to Authenticating and Securing Node.js APIs (20)

PDF
前端MVC 豆瓣说
PPTX
Angular Workshop_Sarajevo2
PDF
Mashing up JavaScript
PDF
Mashing up JavaScript – Advanced Techniques for modern Web Apps
PDF
How to build an AngularJS backend-ready app WITHOUT BACKEND
PDF
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
PDF
Passwords suck, but centralized proprietary services are not the answer
PDF
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
PDF
Doctrine For Beginners
PDF
Virtual Madness @ Etsy
PDF
Burn down the silos! Helping dev and ops gel on high availability websites
PDF
node.js practical guide to serverside javascript
PPTX
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
PDF
Persona: in your browsers, killing your passwords
PDF
KISS: Keep It Simple Security - Oleg Zinchenko - Symfony Cafe Kyiv
PDF
Keep It Simple Security (Symfony cafe 28-01-2016)
PDF
KISS: Keep It Simple Security - Oleg Zinchenko - Symfony Cafe Kyiv
PDF
The Web beyond "usernames & passwords" (OSDC12)
PPTX
Express JS
PDF
Bonnes pratiques de développement avec Node js
前端MVC 豆瓣说
Angular Workshop_Sarajevo2
Mashing up JavaScript
Mashing up JavaScript – Advanced Techniques for modern Web Apps
How to build an AngularJS backend-ready app WITHOUT BACKEND
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Passwords suck, but centralized proprietary services are not the answer
Building Persona: federated and privacy-sensitive identity for the Web (LCA 2...
Doctrine For Beginners
Virtual Madness @ Etsy
Burn down the silos! Helping dev and ops gel on high availability websites
node.js practical guide to serverside javascript
What mom never told you about bundle configurations - Symfony Live Paris 2012
 
Persona: in your browsers, killing your passwords
KISS: Keep It Simple Security - Oleg Zinchenko - Symfony Cafe Kyiv
Keep It Simple Security (Symfony cafe 28-01-2016)
KISS: Keep It Simple Security - Oleg Zinchenko - Symfony Cafe Kyiv
The Web beyond "usernames & passwords" (OSDC12)
Express JS
Bonnes pratiques de développement avec Node js

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
history of c programming in notes for students .pptx
PPT
Introduction Database Management System for Course Database
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Introduction to Artificial Intelligence
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
top salesforce developer skills in 2025.pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
medical staffing services at VALiNTRY
PDF
System and Network Administraation Chapter 3
How to Migrate SBCGlobal Email to Yahoo Easily
Operating system designcfffgfgggggggvggggggggg
How to Choose the Right IT Partner for Your Business in Malaysia
Reimagine Home Health with the Power of Agentic AI​
history of c programming in notes for students .pptx
Introduction Database Management System for Course Database
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Softaken Excel to vCard Converter Software.pdf
Understanding Forklifts - TECH EHS Solution
Wondershare Filmora 15 Crack With Activation Key [2025
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Introduction to Artificial Intelligence
Computer Software and OS of computer science of grade 11.pptx
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
top salesforce developer skills in 2025.pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
medical staffing services at VALiNTRY
System and Network Administraation Chapter 3

Authenticating and Securing Node.js APIs

  • 1. Shubhra Kar | Products & Education twitter:@shubhrakar {“Node.js”: “APIs @hyperscale”}
  • 2. SSL – Setup in Loopback.io $ openssl genrsa -out privatekey.pem 1024 $ openssl req -new -key privatekey.pem -out certrequest.csr $ openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem var path = require('path'), fs = require("fs"); exports.privateKey = fs.readFileSync(path.join(__dirname, './private/privatekey.pem')).toString(); exports.certificate = fs.readFileSync(path.join(__dirname, './private/certificate.pem')).toString();
  • 3. SSL – App Usage in Loopback.io var https = require('https'); var sslConfig = require('./ssl-config'); ... var options = { key: sslConfig.privateKey, cert: sslConfig.certificate }; … server.listen(app.get('port'), function() { var baseUrl = (httpOnly? 'http://' : 'https://') + app.get('host') + ':' + app.get('port'); app.emit('started', baseUrl); console.log('LoopBack server listening @ %s%s', baseUrl, '/'); }); return server;
  • 4. ACL in Loopback.io READ: exists - Boolean method that determines whether a user exists. findById - Find a user by ID. find - Find all users that match specified conditions. findOne - Finds a single user instance that matches specified conditions. count - Returns the number of users that match the specified conditions. WRITE: create - create a new user. updateAttributes (update) - update a user record. upsert (update or insert) - update or insert a new user record. destroyById (equivalent to removeById or deleteById) - delete the user with the specified ID. For other methods, the default access type is EXECUTE; for example, a custom method maps to the EXECUTE access type.
  • 5. Full Stack (MEAN App Angular frontend)
  • 6. Full Stack (Loopback backend API)
  • 7. Full Stack (Loopback backend API Authorization)
  • 8. Static Roles in Loopback.io User.create([ {username: 'John', email: 'john@doe.com', password: 'opensesame'}, {username: 'Jane', email: 'jane@doe.com', password: 'opensesame'}, {username: 'Bob', email: 'bob@projects.com', password: 'opensesame'} ], function(err, users) { if (err) return cb(err); //create the admin role Role.create({ name: 'admin' }, function(err, role) { if (err) cb(err); //make bob an admin role.principals.create({ principalType: RoleMapping.USER, principalId: users[2].id }, function(err, principal) { cb(err); }); }); });
  • 9. Mapping Roles to ACLs { "accessType": "EXECUTE", "principalType": "ROLE", "principalId": "admin", "permission": "ALLOW", "property": "find" }
  • 10. Built in dynamic roles in Loopback.io
  • 11. Built in dynamic roles in Loopback.io module.exports = function(app) { var Role = app.models.Role; Role.registerResolver('teamMember', function(role, context, cb) { function reject(err) { if(err) { return cb(err); } cb(null, false); } if (context.modelName !== 'project') { // the target model is not project return reject(); } var userId = context.accessToken.userId; if (!userId) { return reject(); // do not allow anonymous users }
  • 12. Built in dynamic roles in Loopback.io // check if userId is in team table for the given project id context.model.findById(context.modelId, function(err, project) { if(err || !project) { reject(err); } var Team = app.models.Team; Team.count({ ownerId: project.ownerId, memberId: userId }, function(err, count) { if (err) { return reject(err); } cb(null, count > 0); // true = is a team member }); }); }); };
  • 13. Mapping Dynamic Role to ACLs. { "accessType": "READ", "principalType": "ROLE", "principalId": "teamMember", "permission": "ALLOW", "property": "findById" }
  • 14. OAuth2.0 and JWT in Loopback.io
  • 15. Setup – OAuth 2.0 in Loopback.io npm install loopback-component-oauth2
  • 16. Configuration – OAuth2.0 in Loopback.io var oauth2 = require('loopback-component-oauth2'); var options = { dataSource: app.dataSources.db, // Data source for oAuth2 metadata persistence loginPage: '/login', // The login page URL loginPath: '/login' // The login form processing URL }; oauth2.oAuth2Provider( app, // The app instance options // The options ); oauth2.authenticate(['/protected', '/api', '/me'], {session: false, scope: 'email'})
  • 18. 3rd Party Logins using Passport strategies
  • 19. Setup of passport component in Loopback.io npm install loopback-component-passport
  • 20. Config – Facebook Authentication in Loopback.io { "facebook-login": { "provider": "facebook", "module": "passport-facebook", "clientID": "{facebook-client-id-1}", "clientSecret": "{facebook-client-secret-1}", "callbackURL": "http://localhost:3000/auth/facebook /callback", "authPath": "/auth/facebook", "callbackPath": "/auth/facebook/callback", "successRedirect": "/auth/account", "scope": ["email"] }
  • 21. Config – Google Authentication in Loopback.io { "google-link": { "provider": "google", "module": "passport-google-oauth", "strategy": "OAuth2Strategy", "clientID": "{google-client-id-2}", "clientSecret": "{google-client-secret-2}", "callbackURL": "http://localhost:3000/link/google/ callback", "authPath": "/link/google", "callbackPath": "/link/google/callback", "successRedirect": "/link/account", "scope": ["email", "profile"], "link": true }
  • 22. Config – MS AD Authentication in Loopback.io { "ms-ad": { "provider": "ms-ad", "authScheme":"ldap", "module": "passport-ldapauth", "authPath": "/auth/msad", "successRedirect": "/auth/account", "failureRedirect": "/msad", "failureFlash": true, "session": true, "LdapAttributeForLogin": "mail", "LdapAttributeForUsername": "mail", "LdapAttributeForMail": "mail", "server":{ "url": "ldap://ldap.example.org:389/dc=example,dc=org", "bindDn": "bindUsername", "bindCredentials": "bindPassword", "searchBase": "ou=people,dc=example,dc=org", "searchAttributes": ["cn", "mail", "uid", "givenname"], "searchFilter": "(&(objectcategory=person)(objectclass=user)(|(s amaccountname={{username}})(mail={{username}})))" } }
  • 23. Application Level passport configurator in Loopback // Create an instance of PassportConfigurator with the app instance var PassportConfigurator = require('loopback-component- passport').PassportConfigurator; var passportConfigurator = new PassportConfigurator(app); app.boot(__dirname); ... // Enable http session app.use(loopback.session({ secret: 'keyboard cat' })); // Load the provider configurations var config = {}; try { config = require('./providers.json'); } catch(err) { console.error('Please configure your passport strategy in `providers.json`.'); console.error('Copy `providers.json.template` to `providers.json` and replace the clientID/clientSecret values with your own.'); process.exit(1); }
  • 24. Application Level using Passport configurator // Initialize passport passportConfigurator.init(); // Set up related models passportConfigurator.setupModels({ userModel: app.models.user, userIdentityModel: app.models.userIdentity, userCredentialModel: app.models.userCredential }); // Configure passport strategies for third party auth providers for(var s in config) { var c = config[s]; c.session = c.session !== false; passportConfigurator.configureProvider(s, c); }
  • 26. Security & Social Logins Loopback async API Gateway*