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

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 AngularJSGunnar Hillert
 
Serverless - Developers.IO 2019
Serverless - Developers.IO 2019Serverless - Developers.IO 2019
Serverless - Developers.IO 2019Shuji Watanabe
 
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 iOSFITC
 
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 DevelopmentFITC
 
Local Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothLocal Authentication par Pierre-Alban Toth
Local Authentication par Pierre-Alban TothCocoaHeads France
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web AppsFITC
 
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...Caldera Labs
 
【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践【前端Mvc】之豆瓣说实践
【前端Mvc】之豆瓣说实践taobao.com
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
Google Cloud Endpointsによる API構築
Google Cloud Endpointsによる API構築Google Cloud Endpointsによる API構築
Google Cloud Endpointsによる API構築Keiji Ariyama
 
Chrome enchanted 2015
Chrome enchanted 2015Chrome enchanted 2015
Chrome enchanted 2015Chang W. Doh
 
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 WorkerChang W. Doh
 
Mobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptMobile HTML, CSS, and JavaScript
Mobile HTML, CSS, and JavaScriptfranksvalli
 
Managing JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSManaging JavaScript Dependencies With RequireJS
Managing JavaScript Dependencies With RequireJSDen Odell
 

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

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 MinutesRaymond Feng
 
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 SQLiteSiena Aguayo
 
Rapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRapid API Development with LoopBack/StrongLoop
Rapid API Development with LoopBack/StrongLoopRaymond Camden
 
LoopBack: a productivity booster for MEAN
LoopBack: a productivity booster for MEANLoopBack: a productivity booster for MEAN
LoopBack: a productivity booster for MEANMiroslav Bajtoš
 
Node.js Frameworks & Design Patterns Webinar
Node.js Frameworks & Design Patterns WebinarNode.js Frameworks & Design Patterns Webinar
Node.js Frameworks & Design Patterns WebinarShubhra Kar
 
Toronto node js_meetup
Toronto node js_meetupToronto node js_meetup
Toronto node js_meetupShubhra Kar
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShareSlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

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
 
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 AppsBastian Hofmann
 
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 Enrique Oriol Bermúdez
 
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 ...Francois Marier
 
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 answerFrancois Marier
 
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...Francois Marier
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
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 websitesLindsay Holmwood
 
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 javascriptEldar 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 2012D
 
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 passwordsFrancois Marier
 
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 KyivGrossum Software Outsourcing
 
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 KyivGrossum
 
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)Oleg Zinchenko
 
The Web beyond "usernames & passwords" (OSDC12)
The Web beyond "usernames & passwords" (OSDC12)The Web beyond "usernames & passwords" (OSDC12)
The Web beyond "usernames & passwords" (OSDC12)Francois Marier
 
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 jsFrancois Zaninotto
 

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

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 

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.