SlideShare a Scribd company logo
1 of 29
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'})
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*
Micro services scaling
Hyper-scale & Micro-services Deployment

More Related Content

What's hot

Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 
Building Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSBuilding Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOS
FITC
 
Angular vs React for Web Application Development
Angular vs React for Web Application DevelopmentAngular vs React for Web Application Development
Angular vs React for Web Application Development
FITC
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践
taobao.com
 

What's hot (20)

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

Viewers also liked

Viewers also liked (10)

Building a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 MinutesBuilding a Node.js API backend with LoopBack in 5 Minutes
Building a Node.js API backend with LoopBack in 5 Minutes
 
Gotta Persist 'Em All: Realm as Replacement for SQLite
Gotta Persist 'Em All: Realm as Replacement for SQLiteGotta Persist 'Em All: Realm as Replacement for SQLite
Gotta Persist 'Em All: Realm as Replacement for SQLite
 
Rapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoop
 
Loopback
LoopbackLoopback
Loopback
 
LoopBack: a productivity booster for MEAN
LoopBack: a productivity booster for MEANLoopBack: a productivity booster for MEAN
LoopBack: a productivity booster for MEAN
 
Node.js Frameworks & Design Patterns Webinar
Node.js Frameworks & Design Patterns WebinarNode.js Frameworks & Design Patterns Webinar
Node.js Frameworks & Design Patterns Webinar
 
Toronto node js_meetup
Toronto node js_meetupToronto node js_meetup
Toronto node js_meetup
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Authenticating and Securing Node.js APIs

前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
Eldar Djafarov
 
What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012What mom never told you about bundle configurations - Symfony Live Paris 2012
What mom never told you about bundle configurations - Symfony Live Paris 2012
D
 

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

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

Recently uploaded

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

Recently uploaded (20)

WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 

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'})
  • 17.
  • 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*
  • 27.