SlideShare a Scribd company logo
1 of 41
Download to read offline
Modern API Security with!
JSON Web Tokens!
Jonathan LeBlanc !
Twitter: @jcleblanc !
Book: http://bit.ly/iddatasecurity!
JSON Web Token (JWT) Specification!
!
https://tools.ietf.org/html/rfc7519!
JWT Benefits!
!
They’re self contained and help maintain a stateless
architecture.!
!
They maintain a small footprint and can be passed along
easily. !
!
They work well across multiple programming languages.!
Traditional vs Token-Based
Authentication Systems!
User logs in, server checks creds	
Session stored in sever, cookie created	
Send session data to access endpoints	
Traditional Authentication Systems
Issues with traditional systems!
•  Sessions: Record needs to be stored on server !
•  Scalability: With sessions in memory, load increases
drastically in a distributed system.!
•  CORS: When using multiple devices grabbing data via AJAX
requests, we may run into forbidden requests.!
•  CSRF Attacks: Riding session data to send commands to
server from a browser that is trusted via session.!
User logs in, server checks creds	
Token generated, store in localStorage	
Provide token in headers for all reqs	
Token-Based Authentication Systems
How JSON Web Tokens Work!
•  Header: Token type and hashing algorithm!
•  Payload: User / verification content!
•  Signature: Header, payload, and secret!
XXXXXXXX.YYYYYYYY.ZZZZZZZZ!
What a Signed Token will Look Like!
Authorization: Bearer <token>!
Transmission of a JWT via HTTP Headers!
JWT Header!
!
alg: The hashing algorithm to be used.!
!
typ: The token type. Should be JWT.!
var header_data = {!
alg: 'RSA', !
typ: 'JWT' !
};!
Example JWT Header!
Difference between HMAC SHA256 and RSA SHA256
hashing algorithms!
!
HMAC SHA256: Symmetric key cryptography, single shared
private key. Faster, good between trusted parties.!
!
RSA SHA256: Asymmetric key cryptography, public /
private keys. Slower, good between untrusted parties.!
JWT Payload (Claims)!
!
Reserved: Predefined, recommended, interoperable terms. !
!
Public: Customs claims that may be set at will.!
!
Private: Agreed upon claims between two parties.!
Reserved Claims!
!
iss (issuer): The person that issued the token.!
sub (subject) : The subject of the token.!
aud (audience) : Audience the token is intended for.!
exp (expiration time) : Expiration time of the token.!
nbf (not before) : Starting time token is available.!
iat (issued at) : When the token was issued.!
jti (JWT ID) : Unique identifier for the token. !
!
var payload = {!
sub: '4355676',!
exp: '1481160294',!
jti: '841112',!
role: 'admin'!
};!
Example JWT Payload!
JWT Signature!
!
Encoded Data: Base64 encoded header + payload!
!
Secret: A private key.!
var header = {!
alg: 'RSA', !
typ: 'JWT' !
};!
!
var payload = {!
sub: '4355676',!
exp: '1481160294',!
jti: '841112’!
};!
!
HMACSHA256(!
base64UrlEncode(header) + "." +!
base64UrlEncode(payload),!
secret)!
Creating a JWT signature!
// generate private key!
openssl genrsa -out private.pem 2048!
!
// generate public key!
openssl rsa -in private.pem -outform PEM -pubout -out public.pem!
Creating new public / private keys (minus password for testing)!
var fs = require('fs'), !
ursa = require('ursa');!
!
// set up public / private keys!
var key = ursa.generatePrivateKey(), !
privatepem = key.toPrivatePem(),!
publicpem = key.toPublicPem();!
!
// store keys in .pem files !
try {!
fs.writeFileSync('private.pem', privatepem, 'ascii');!
fs.writeFileSync('public.pem', publicpem, 'ascii');!
} catch (err) {!
console.error(err);!
}!
Writing new public / private keys to the file system!
var jwt = require('jsonwebtoken'),!
fs = require('fs');!
!
// get private key!
var cert = fs.readFileSync('private.pem');!
!
// sign asynchronously with RSA SHA256 !
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {!
console.log(token);!
});!
Signing JSON Web Tokens !
eyJhbGciOiJSU0EiLCJ0eXAiOiJKV1QifQ.eyJzdWIiOiJ0b21Ac3Rvcm1wYXRoLmNvbSIsIm5hb
WUiOiJUb20gQWJib3R0Iiwicm9sZSI6InVzZXIifQ.Yjc3YzdkZmQ4OTM1ZjA4MDM0OTdhOTkyMz
ZhM2ZiZjZjNzVkZjIzOWJmMGM5YmU4MWZiYjY1MmY1YjRkNWY1ZA!
Signed Token!
var jwt = require('jsonwebtoken'),!
fs = require('fs');!
!
//get public key !
cert = fs.readFileSync('public.pem'); !
!
// verify asynchronously with RSA SHA256!
jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {!
console.log(payload);!
});!
Verifying JSON Web Tokens!
Securing JWTs!
Securing JWTs!
!
•  Verify signature before trusting data in the JWT.!
•  Secure the secret key used for signing. Keys should
only be accessible by the issuer and consumer.!
•  Do not add sensitive data to the JWT. They are signed
to protect against manipulation, not encrypted.!
Preventing Replay Attacks!
!
To prevent replay attacks, include the following claims
to the JWT payload:!
!
•  jti (JWT ID): Random or pseudo-random nonce.!
•  exp (expiration): Time the token expires.!
•  iat (issued at): Time the token was issued. !
JSON Web Encryption (JWE) Specification!
!
https://tools.ietf.org/html/rfc7516 !
Mixing JWTs with OAuth 2!
Benefits of the Specification!
!
Existing Trust Relationships: If a site has an existing
user relationship, that may be used.!
A Bit of History!
!
OAuth, OpenID, authorization and
authentication!
JSON Web Token (JWT) Profile for OAuth 2.0
Client Authentication and Authorization Grants!
!
https://tools.ietf.org/pdf/rfc7523.pdf!
"JWT vs OAuth" is a comparison of apples and
apple carts!
!
JWT: Authentication protocol!
OAuth: Distributed authorization framework !
User is forwarded to sign in, grant
permissions	
Code is provided back in URI	
Request to exchange code for token	
How the OAuth 2 Process Generally Works	
Access Token is provided back
POST /token.oauth2 HTTP/1.1!
Host: service.example.com!
Content-Type: application/x-www-form-urlencoded!
!
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer!
&assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6IjE2In0.!
eyJpc3Mi[...omitted for brevity...].!
J9l-ZhwP[...omitted for brevity...]!
Authorization Example OAuth 2 access token request with JWT!
POST /token.oauth2 HTTP/1.1!
Host: service.example.com!
Content-Type: application/x-www-form-urlencoded!
!
grant_type=authorization_code&!
code=n0esc3NRze7LTCu7iYzS6a5acc3f0ogp4&!
client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-
bearer!
client_assertion=eyJhbGciOiJSUzI1NiIsImtpZCI6IjIyIn0.!
eyJpc3Mi[...omitted for brevity...].!
cC4hiUPo[...omitted for brevity...]!
Authentication Example OAuth 2 access token request with JWT!
Validating the JWT!
!
•  iss (required): Unique issuer identity claim.!
•  sub (required): Identity the token subject!
•  Authorization: ID of a valid delegate. !
•  Authentication: The OAuth 2 client ID.!
•  aud (required): Identity of the authorization server,
such as the URI endpoint. !
Validating the JWT!
!
•  exp (required): Expiration to limit the time that the
JWT can be used.!
•  nbf (optional): Time before which token must not be
accepted.!
•  jti (optional): Uniquely identifies the token.!
•  other claims (optional): Any other claims may be
present.!
Validating the JWT!
!
•  Digitally signed / Message Authentication Code: A
valid signature / MAC must be present.!
•  Valid JWT: Must conform to the makeup of a JWT.!
Links and More Information!
•  Specifications: !
•  JWT: https://tools.ietf.org/html/rfc7519!
•  JWT / OAuth2: https://tools.ietf.org/html/rfc7523!
•  JSON Web Encryption: https://tools.ietf.org/html/
rfc7516!
•  JWT Website: https://jwt.io/!
•  jsonwebtoken NPM module: https://www.npmjs.com/package/
jsonwebtoken!
Thank You!!
Slides: slideshare.net/jcleblanc!
Jonathan LeBlanc !
Twitter: @jcleblanc !
Book: http://bit.ly/iddatasecurity!

More Related Content

What's hot

Introduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityIntroduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityBruno Henrique Rother
 
OAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveOAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveNordic APIs
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2Sanjoy Kumar Roy
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 
OAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId ConnectOAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId ConnectSaran Doraiswamy
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityMohammed Fazuluddin
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongDerek Perkins
 
OAuth - Open API Authentication
OAuth - Open API AuthenticationOAuth - Open API Authentication
OAuth - Open API Authenticationleahculver
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An OverviewPat Patterson
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host headerSergey Belov
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloakGuy Marom
 
Getting Started With WebAuthn
Getting Started With WebAuthnGetting Started With WebAuthn
Getting Started With WebAuthnFIDO Alliance
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2Aaron Parecki
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourSoroush Dalili
 

What's hot (20)

Introduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring SecurityIntroduction to JWT and How to integrate with Spring Security
Introduction to JWT and How to integrate with Spring Security
 
JSON WEB TOKEN
JSON WEB TOKENJSON WEB TOKEN
JSON WEB TOKEN
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
OpenID Connect Explained
OpenID Connect ExplainedOpenID Connect Explained
OpenID Connect Explained
 
OAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep DiveOAuth & OpenID Connect Deep Dive
OAuth & OpenID Connect Deep Dive
 
An introduction to OAuth 2
An introduction to OAuth 2An introduction to OAuth 2
An introduction to OAuth 2
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
OAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId ConnectOAuth 2.0 and OpenId Connect
OAuth 2.0 and OpenId Connect
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
Rest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API SecurityRest API Security - A quick understanding of Rest API Security
Rest API Security - A quick understanding of Rest API Security
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
NestJS
NestJSNestJS
NestJS
 
OAuth - Open API Authentication
OAuth - Open API AuthenticationOAuth - Open API Authentication
OAuth - Open API Authentication
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An Overview
 
Attacking thru HTTP Host header
Attacking thru HTTP Host headerAttacking thru HTTP Host header
Attacking thru HTTP Host header
 
Secure your app with keycloak
Secure your app with keycloakSecure your app with keycloak
Secure your app with keycloak
 
Getting Started With WebAuthn
Getting Started With WebAuthnGetting Started With WebAuthn
Getting Started With WebAuthn
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ BehaviourWAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
WAF Bypass Techniques - Using HTTP Standard and Web Servers’ Behaviour
 

Similar to Modern API Security with JSON Web Tokens

I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)Joel Lord
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsrobertjd
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationStormpath
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)Joel Lord
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)Joel Lord
 
Autenticação com Json Web Token (JWT)
Autenticação com Json Web Token (JWT)Autenticação com Json Web Token (JWT)
Autenticação com Json Web Token (JWT)Ivan Rosolen
 
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Building Secure User Interfaces With JWTs (JSON Web Tokens)Building Secure User Interfaces With JWTs (JSON Web Tokens)
Building Secure User Interfaces With JWTs (JSON Web Tokens)Stormpath
 
I Don't Care About Security
I Don't Care About Security I Don't Care About Security
I Don't Care About Security Joel Lord
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationErick Belluci Tedeschi
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)iMasters
 
Node.js Authentication and Data Security
Node.js Authentication and Data SecurityNode.js Authentication and Data Security
Node.js Authentication and Data SecurityJonathan LeBlanc
 
[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokensOWASP
 
Token Authentication for Java Applications
Token Authentication for Java ApplicationsToken Authentication for Java Applications
Token Authentication for Java ApplicationsStormpath
 
The Ultimate Guide to Mobile API Security
The Ultimate Guide to Mobile API SecurityThe Ultimate Guide to Mobile API Security
The Ultimate Guide to Mobile API SecurityStormpath
 
JWT Authentication with AngularJS
JWT Authentication with AngularJSJWT Authentication with AngularJS
JWT Authentication with AngularJSrobertjd
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJohn Anderson
 
REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!Stormpath
 
Jwt with flask slide deck - alan swenson
Jwt with flask   slide deck - alan swensonJwt with flask   slide deck - alan swenson
Jwt with flask slide deck - alan swensonJeffrey Clark
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and PracticesPrabath Siriwardena
 

Similar to Modern API Security with JSON Web Tokens (20)

I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token Authentication
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
 
I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)I Don't Care About Security (And Neither Should You)
I Don't Care About Security (And Neither Should You)
 
Autenticação com Json Web Token (JWT)
Autenticação com Json Web Token (JWT)Autenticação com Json Web Token (JWT)
Autenticação com Json Web Token (JWT)
 
Building Secure User Interfaces With JWTs (JSON Web Tokens)
Building Secure User Interfaces With JWTs (JSON Web Tokens)Building Secure User Interfaces With JWTs (JSON Web Tokens)
Building Secure User Interfaces With JWTs (JSON Web Tokens)
 
I Don't Care About Security
I Don't Care About Security I Don't Care About Security
I Don't Care About Security
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs Authorization
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)PHP Experience 2016 - [Palestra] Json Web Token (JWT)
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
 
SSl/TLS Analysis
SSl/TLS AnalysisSSl/TLS Analysis
SSl/TLS Analysis
 
Node.js Authentication and Data Security
Node.js Authentication and Data SecurityNode.js Authentication and Data Security
Node.js Authentication and Data Security
 
[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens[OPD 2019] Attacking JWT tokens
[OPD 2019] Attacking JWT tokens
 
Token Authentication for Java Applications
Token Authentication for Java ApplicationsToken Authentication for Java Applications
Token Authentication for Java Applications
 
The Ultimate Guide to Mobile API Security
The Ultimate Guide to Mobile API SecurityThe Ultimate Guide to Mobile API Security
The Ultimate Guide to Mobile API Security
 
JWT Authentication with AngularJS
JWT Authentication with AngularJSJWT Authentication with AngularJS
JWT Authentication with AngularJS
 
JSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your LifeJSON Web Tokens Will Improve Your Life
JSON Web Tokens Will Improve Your Life
 
REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!REST API Security: OAuth 2.0, JWTs, and More!
REST API Security: OAuth 2.0, JWTs, and More!
 
Jwt with flask slide deck - alan swenson
Jwt with flask   slide deck - alan swensonJwt with flask   slide deck - alan swenson
Jwt with flask slide deck - alan swenson
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and Practices
 

More from Jonathan LeBlanc

JavaScript App Security: Auth and Identity on the Client
JavaScript App Security: Auth and Identity on the ClientJavaScript App Security: Auth and Identity on the Client
JavaScript App Security: Auth and Identity on the ClientJonathan LeBlanc
 
Improving Developer Onboarding Through Intelligent Data Insights
Improving Developer Onboarding Through Intelligent Data InsightsImproving Developer Onboarding Through Intelligent Data Insights
Improving Developer Onboarding Through Intelligent Data InsightsJonathan LeBlanc
 
Better Data with Machine Learning and Serverless
Better Data with Machine Learning and ServerlessBetter Data with Machine Learning and Serverless
Better Data with Machine Learning and ServerlessJonathan LeBlanc
 
Best Practices for Application Development with Box
Best Practices for Application Development with BoxBest Practices for Application Development with Box
Best Practices for Application Development with BoxJonathan LeBlanc
 
Box Platform Developer Workshop
Box Platform Developer WorkshopBox Platform Developer Workshop
Box Platform Developer WorkshopJonathan LeBlanc
 
Modern Cloud Data Security Practices
Modern Cloud Data Security PracticesModern Cloud Data Security Practices
Modern Cloud Data Security PracticesJonathan LeBlanc
 
Understanding Box UI Elements
Understanding Box UI ElementsUnderstanding Box UI Elements
Understanding Box UI ElementsJonathan LeBlanc
 
Understanding Box applications, tokens, and scoping
Understanding Box applications, tokens, and scopingUnderstanding Box applications, tokens, and scoping
Understanding Box applications, tokens, and scopingJonathan LeBlanc
 
The Future of Online Money: Creating Secure Payments Globally
The Future of Online Money: Creating Secure Payments GloballyThe Future of Online Money: Creating Secure Payments Globally
The Future of Online Money: Creating Secure Payments GloballyJonathan LeBlanc
 
Creating an In-Aisle Purchasing System from Scratch
Creating an In-Aisle Purchasing System from ScratchCreating an In-Aisle Purchasing System from Scratch
Creating an In-Aisle Purchasing System from ScratchJonathan LeBlanc
 
Secure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaSecure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaJonathan LeBlanc
 
Protecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsProtecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsJonathan LeBlanc
 
PHP Identity and Data Security
PHP Identity and Data SecurityPHP Identity and Data Security
PHP Identity and Data SecurityJonathan LeBlanc
 
Secure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaSecure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaJonathan LeBlanc
 
Protecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsProtecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsJonathan LeBlanc
 
Future of Identity, Data, and Wearable Security
Future of Identity, Data, and Wearable SecurityFuture of Identity, Data, and Wearable Security
Future of Identity, Data, and Wearable SecurityJonathan LeBlanc
 

More from Jonathan LeBlanc (20)

JavaScript App Security: Auth and Identity on the Client
JavaScript App Security: Auth and Identity on the ClientJavaScript App Security: Auth and Identity on the Client
JavaScript App Security: Auth and Identity on the Client
 
Improving Developer Onboarding Through Intelligent Data Insights
Improving Developer Onboarding Through Intelligent Data InsightsImproving Developer Onboarding Through Intelligent Data Insights
Improving Developer Onboarding Through Intelligent Data Insights
 
Better Data with Machine Learning and Serverless
Better Data with Machine Learning and ServerlessBetter Data with Machine Learning and Serverless
Better Data with Machine Learning and Serverless
 
Best Practices for Application Development with Box
Best Practices for Application Development with BoxBest Practices for Application Development with Box
Best Practices for Application Development with Box
 
Box Platform Overview
Box Platform OverviewBox Platform Overview
Box Platform Overview
 
Box Platform Developer Workshop
Box Platform Developer WorkshopBox Platform Developer Workshop
Box Platform Developer Workshop
 
Modern Cloud Data Security Practices
Modern Cloud Data Security PracticesModern Cloud Data Security Practices
Modern Cloud Data Security Practices
 
Box Authentication Types
Box Authentication TypesBox Authentication Types
Box Authentication Types
 
Understanding Box UI Elements
Understanding Box UI ElementsUnderstanding Box UI Elements
Understanding Box UI Elements
 
Understanding Box applications, tokens, and scoping
Understanding Box applications, tokens, and scopingUnderstanding Box applications, tokens, and scoping
Understanding Box applications, tokens, and scoping
 
The Future of Online Money: Creating Secure Payments Globally
The Future of Online Money: Creating Secure Payments GloballyThe Future of Online Money: Creating Secure Payments Globally
The Future of Online Money: Creating Secure Payments Globally
 
Creating an In-Aisle Purchasing System from Scratch
Creating an In-Aisle Purchasing System from ScratchCreating an In-Aisle Purchasing System from Scratch
Creating an In-Aisle Purchasing System from Scratch
 
Secure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaSecure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication Media
 
Protecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsProtecting the Future of Mobile Payments
Protecting the Future of Mobile Payments
 
PHP Identity and Data Security
PHP Identity and Data SecurityPHP Identity and Data Security
PHP Identity and Data Security
 
Secure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication MediaSecure Payments Over Mixed Communication Media
Secure Payments Over Mixed Communication Media
 
Protecting the Future of Mobile Payments
Protecting the Future of Mobile PaymentsProtecting the Future of Mobile Payments
Protecting the Future of Mobile Payments
 
Future of Identity, Data, and Wearable Security
Future of Identity, Data, and Wearable SecurityFuture of Identity, Data, and Wearable Security
Future of Identity, Data, and Wearable Security
 
Kill All Passwords
Kill All PasswordsKill All Passwords
Kill All Passwords
 
BattleHack Los Angeles
BattleHack Los Angeles BattleHack Los Angeles
BattleHack Los Angeles
 

Recently uploaded

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Recently uploaded (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Modern API Security with JSON Web Tokens

  • 1. Modern API Security with! JSON Web Tokens! Jonathan LeBlanc ! Twitter: @jcleblanc ! Book: http://bit.ly/iddatasecurity!
  • 2. JSON Web Token (JWT) Specification! ! https://tools.ietf.org/html/rfc7519!
  • 3. JWT Benefits! ! They’re self contained and help maintain a stateless architecture.! ! They maintain a small footprint and can be passed along easily. ! ! They work well across multiple programming languages.!
  • 5. User logs in, server checks creds Session stored in sever, cookie created Send session data to access endpoints Traditional Authentication Systems
  • 6. Issues with traditional systems! •  Sessions: Record needs to be stored on server ! •  Scalability: With sessions in memory, load increases drastically in a distributed system.! •  CORS: When using multiple devices grabbing data via AJAX requests, we may run into forbidden requests.! •  CSRF Attacks: Riding session data to send commands to server from a browser that is trusted via session.!
  • 7. User logs in, server checks creds Token generated, store in localStorage Provide token in headers for all reqs Token-Based Authentication Systems
  • 8. How JSON Web Tokens Work!
  • 9. •  Header: Token type and hashing algorithm! •  Payload: User / verification content! •  Signature: Header, payload, and secret!
  • 11. Authorization: Bearer <token>! Transmission of a JWT via HTTP Headers!
  • 12. JWT Header! ! alg: The hashing algorithm to be used.! ! typ: The token type. Should be JWT.!
  • 13. var header_data = {! alg: 'RSA', ! typ: 'JWT' ! };! Example JWT Header!
  • 14. Difference between HMAC SHA256 and RSA SHA256 hashing algorithms! ! HMAC SHA256: Symmetric key cryptography, single shared private key. Faster, good between trusted parties.! ! RSA SHA256: Asymmetric key cryptography, public / private keys. Slower, good between untrusted parties.!
  • 15. JWT Payload (Claims)! ! Reserved: Predefined, recommended, interoperable terms. ! ! Public: Customs claims that may be set at will.! ! Private: Agreed upon claims between two parties.!
  • 16. Reserved Claims! ! iss (issuer): The person that issued the token.! sub (subject) : The subject of the token.! aud (audience) : Audience the token is intended for.! exp (expiration time) : Expiration time of the token.! nbf (not before) : Starting time token is available.! iat (issued at) : When the token was issued.! jti (JWT ID) : Unique identifier for the token. ! !
  • 17. var payload = {! sub: '4355676',! exp: '1481160294',! jti: '841112',! role: 'admin'! };! Example JWT Payload!
  • 18. JWT Signature! ! Encoded Data: Base64 encoded header + payload! ! Secret: A private key.!
  • 19. var header = {! alg: 'RSA', ! typ: 'JWT' ! };! ! var payload = {! sub: '4355676',! exp: '1481160294',! jti: '841112’! };! ! HMACSHA256(! base64UrlEncode(header) + "." +! base64UrlEncode(payload),! secret)! Creating a JWT signature!
  • 20. // generate private key! openssl genrsa -out private.pem 2048! ! // generate public key! openssl rsa -in private.pem -outform PEM -pubout -out public.pem! Creating new public / private keys (minus password for testing)!
  • 21. var fs = require('fs'), ! ursa = require('ursa');! ! // set up public / private keys! var key = ursa.generatePrivateKey(), ! privatepem = key.toPrivatePem(),! publicpem = key.toPublicPem();! ! // store keys in .pem files ! try {! fs.writeFileSync('private.pem', privatepem, 'ascii');! fs.writeFileSync('public.pem', publicpem, 'ascii');! } catch (err) {! console.error(err);! }! Writing new public / private keys to the file system!
  • 22. var jwt = require('jsonwebtoken'),! fs = require('fs');! ! // get private key! var cert = fs.readFileSync('private.pem');! ! // sign asynchronously with RSA SHA256 ! jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err, token) {! console.log(token);! });! Signing JSON Web Tokens !
  • 24. var jwt = require('jsonwebtoken'),! fs = require('fs');! ! //get public key ! cert = fs.readFileSync('public.pem'); ! ! // verify asynchronously with RSA SHA256! jwt.verify(token, cert, { algorithms: ['RS256'] }, function (err, payload) {! console.log(payload);! });! Verifying JSON Web Tokens!
  • 26. Securing JWTs! ! •  Verify signature before trusting data in the JWT.! •  Secure the secret key used for signing. Keys should only be accessible by the issuer and consumer.! •  Do not add sensitive data to the JWT. They are signed to protect against manipulation, not encrypted.!
  • 27. Preventing Replay Attacks! ! To prevent replay attacks, include the following claims to the JWT payload:! ! •  jti (JWT ID): Random or pseudo-random nonce.! •  exp (expiration): Time the token expires.! •  iat (issued at): Time the token was issued. !
  • 28. JSON Web Encryption (JWE) Specification! ! https://tools.ietf.org/html/rfc7516 !
  • 29. Mixing JWTs with OAuth 2!
  • 30. Benefits of the Specification! ! Existing Trust Relationships: If a site has an existing user relationship, that may be used.!
  • 31. A Bit of History! ! OAuth, OpenID, authorization and authentication!
  • 32. JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants! ! https://tools.ietf.org/pdf/rfc7523.pdf!
  • 33. "JWT vs OAuth" is a comparison of apples and apple carts! ! JWT: Authentication protocol! OAuth: Distributed authorization framework !
  • 34. User is forwarded to sign in, grant permissions Code is provided back in URI Request to exchange code for token How the OAuth 2 Process Generally Works Access Token is provided back
  • 35. POST /token.oauth2 HTTP/1.1! Host: service.example.com! Content-Type: application/x-www-form-urlencoded! ! grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer! &assertion=eyJhbGciOiJFUzI1NiIsImtpZCI6IjE2In0.! eyJpc3Mi[...omitted for brevity...].! J9l-ZhwP[...omitted for brevity...]! Authorization Example OAuth 2 access token request with JWT!
  • 36. POST /token.oauth2 HTTP/1.1! Host: service.example.com! Content-Type: application/x-www-form-urlencoded! ! grant_type=authorization_code&! code=n0esc3NRze7LTCu7iYzS6a5acc3f0ogp4&! client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt- bearer! client_assertion=eyJhbGciOiJSUzI1NiIsImtpZCI6IjIyIn0.! eyJpc3Mi[...omitted for brevity...].! cC4hiUPo[...omitted for brevity...]! Authentication Example OAuth 2 access token request with JWT!
  • 37. Validating the JWT! ! •  iss (required): Unique issuer identity claim.! •  sub (required): Identity the token subject! •  Authorization: ID of a valid delegate. ! •  Authentication: The OAuth 2 client ID.! •  aud (required): Identity of the authorization server, such as the URI endpoint. !
  • 38. Validating the JWT! ! •  exp (required): Expiration to limit the time that the JWT can be used.! •  nbf (optional): Time before which token must not be accepted.! •  jti (optional): Uniquely identifies the token.! •  other claims (optional): Any other claims may be present.!
  • 39. Validating the JWT! ! •  Digitally signed / Message Authentication Code: A valid signature / MAC must be present.! •  Valid JWT: Must conform to the makeup of a JWT.!
  • 40. Links and More Information! •  Specifications: ! •  JWT: https://tools.ietf.org/html/rfc7519! •  JWT / OAuth2: https://tools.ietf.org/html/rfc7523! •  JSON Web Encryption: https://tools.ietf.org/html/ rfc7516! •  JWT Website: https://jwt.io/! •  jsonwebtoken NPM module: https://www.npmjs.com/package/ jsonwebtoken!
  • 41. Thank You!! Slides: slideshare.net/jcleblanc! Jonathan LeBlanc ! Twitter: @jcleblanc ! Book: http://bit.ly/iddatasecurity!