SlideShare a Scribd company logo
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 (20)

PDF
JSON Web Token
Deddy Setyadi
 
PDF
Json web token
Mayank Patel
 
PPTX
An introduction to OAuth 2
Sanjoy Kumar Roy
 
PDF
Authentication: Cookies vs JWTs and why you’re doing it wrong
Derek Perkins
 
PPTX
Building Secure User Interfaces With JWTs
robertjd
 
PPTX
An Introduction to OAuth 2
Aaron Parecki
 
PPTX
Web API authentication and authorization
Chalermpon Areepong
 
PDF
Introduction to JWT and How to integrate with Spring Security
Bruno Henrique Rother
 
PDF
Introduction to OpenID Connect
Nat Sakimura
 
PPTX
An Introduction to OAuth2
Aaron Parecki
 
PDF
Demystifying OAuth 2.0
Karl McGuinness
 
PDF
OAuth & OpenID Connect Deep Dive
Nordic APIs
 
PDF
Building layers of defense for your application
VMware Tanzu
 
PDF
Stateless Auth using OAUTH2 & JWT
Mobiliya
 
PPTX
Injection flaws
DANISH INAMDAR
 
PDF
OpenID Connect Explained
Vladimir Dzhuvinov
 
ODP
OAuth2 - Introduction
Knoldus Inc.
 
PPTX
Json web tokens
ElieHannouch
 
PDF
Implementing OAuth
leahculver
 
PPTX
REST API 설계
Terry Cho
 
JSON Web Token
Deddy Setyadi
 
Json web token
Mayank Patel
 
An introduction to OAuth 2
Sanjoy Kumar Roy
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Derek Perkins
 
Building Secure User Interfaces With JWTs
robertjd
 
An Introduction to OAuth 2
Aaron Parecki
 
Web API authentication and authorization
Chalermpon Areepong
 
Introduction to JWT and How to integrate with Spring Security
Bruno Henrique Rother
 
Introduction to OpenID Connect
Nat Sakimura
 
An Introduction to OAuth2
Aaron Parecki
 
Demystifying OAuth 2.0
Karl McGuinness
 
OAuth & OpenID Connect Deep Dive
Nordic APIs
 
Building layers of defense for your application
VMware Tanzu
 
Stateless Auth using OAUTH2 & JWT
Mobiliya
 
Injection flaws
DANISH INAMDAR
 
OpenID Connect Explained
Vladimir Dzhuvinov
 
OAuth2 - Introduction
Knoldus Inc.
 
Json web tokens
ElieHannouch
 
Implementing OAuth
leahculver
 
REST API 설계
Terry Cho
 

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

PDF
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
iMasters
 
PDF
Autenticação com Json Web Token (JWT)
Ivan Rosolen
 
PDF
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Luciano Mammino
 
PPTX
JWT_Presentation to show how jwt is better then session based authorization
nathakash343
 
PDF
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Luciano Mammino
 
PDF
The Hacker's Guide to JWT Security
Patrycja Wegrzynowicz
 
PDF
Jwt with flask slide deck - alan swenson
Jeffrey Clark
 
PDF
What the Heck is OAuth and OpenID Connect - DOSUG 2018
Matt Raible
 
PDF
Json web token api authorization
Giulio De Donato
 
PDF
The Hacker's Guide to JWT Security
Patrycja Wegrzynowicz
 
PPTX
JsonWebTokens ppt - explains JWT, JWS , JWE Tokens
nagarajapallafl
 
PDF
apidays LIVE Australia 2020 - WT* is JWT? by Maciej Treder
apidays
 
PDF
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays
 
PDF
apidays LIVE Paris - WT* is JWT? by Maciej Treder
apidays
 
PDF
apidays LIVE LONDON - WT* is JWT? by Maciej Treder
apidays
 
PDF
apidays LIVE Hong Kong - WT* is JWT? by Maciej Treder
apidays
 
PDF
Securing Web Applications with Token Authentication
Stormpath
 
PPTX
REST Service Authetication with TLS & JWTs
Jon Todd
 
PDF
JSON Web Tokens Will Improve Your Life
John Anderson
 
PHP Experience 2016 - [Palestra] Json Web Token (JWT)
iMasters
 
Autenticação com Json Web Token (JWT)
Ivan Rosolen
 
Cracking JWT tokens: a tale of magic, Node.JS and parallel computing - Node.j...
Luciano Mammino
 
JWT_Presentation to show how jwt is better then session based authorization
nathakash343
 
Cracking JWT tokens: a tale of magic, Node.js and parallel computing - Code E...
Luciano Mammino
 
The Hacker's Guide to JWT Security
Patrycja Wegrzynowicz
 
Jwt with flask slide deck - alan swenson
Jeffrey Clark
 
What the Heck is OAuth and OpenID Connect - DOSUG 2018
Matt Raible
 
Json web token api authorization
Giulio De Donato
 
The Hacker's Guide to JWT Security
Patrycja Wegrzynowicz
 
JsonWebTokens ppt - explains JWT, JWS , JWE Tokens
nagarajapallafl
 
apidays LIVE Australia 2020 - WT* is JWT? by Maciej Treder
apidays
 
apidays LIVE New York - WT* is JWT? by Maciej Treder
apidays
 
apidays LIVE Paris - WT* is JWT? by Maciej Treder
apidays
 
apidays LIVE LONDON - WT* is JWT? by Maciej Treder
apidays
 
apidays LIVE Hong Kong - WT* is JWT? by Maciej Treder
apidays
 
Securing Web Applications with Token Authentication
Stormpath
 
REST Service Authetication with TLS & JWTs
Jon Todd
 
JSON Web Tokens Will Improve Your Life
John Anderson
 
Ad

More from Jonathan LeBlanc (20)

PDF
JavaScript App Security: Auth and Identity on the Client
Jonathan LeBlanc
 
PDF
Improving Developer Onboarding Through Intelligent Data Insights
Jonathan LeBlanc
 
PDF
Better Data with Machine Learning and Serverless
Jonathan LeBlanc
 
PPTX
Best Practices for Application Development with Box
Jonathan LeBlanc
 
PPTX
Box Platform Overview
Jonathan LeBlanc
 
PPTX
Box Platform Developer Workshop
Jonathan LeBlanc
 
PPTX
Modern Cloud Data Security Practices
Jonathan LeBlanc
 
PPTX
Box Authentication Types
Jonathan LeBlanc
 
PPTX
Understanding Box UI Elements
Jonathan LeBlanc
 
PPTX
Understanding Box applications, tokens, and scoping
Jonathan LeBlanc
 
PPTX
The Future of Online Money: Creating Secure Payments Globally
Jonathan LeBlanc
 
PPTX
Creating an In-Aisle Purchasing System from Scratch
Jonathan LeBlanc
 
PDF
Secure Payments Over Mixed Communication Media
Jonathan LeBlanc
 
PDF
Protecting the Future of Mobile Payments
Jonathan LeBlanc
 
PDF
Node.js Authentication and Data Security
Jonathan LeBlanc
 
PDF
PHP Identity and Data Security
Jonathan LeBlanc
 
PPTX
Secure Payments Over Mixed Communication Media
Jonathan LeBlanc
 
PDF
Protecting the Future of Mobile Payments
Jonathan LeBlanc
 
PPTX
Future of Identity, Data, and Wearable Security
Jonathan LeBlanc
 
PDF
Kill All Passwords
Jonathan LeBlanc
 
JavaScript App Security: Auth and Identity on the Client
Jonathan LeBlanc
 
Improving Developer Onboarding Through Intelligent Data Insights
Jonathan LeBlanc
 
Better Data with Machine Learning and Serverless
Jonathan LeBlanc
 
Best Practices for Application Development with Box
Jonathan LeBlanc
 
Box Platform Overview
Jonathan LeBlanc
 
Box Platform Developer Workshop
Jonathan LeBlanc
 
Modern Cloud Data Security Practices
Jonathan LeBlanc
 
Box Authentication Types
Jonathan LeBlanc
 
Understanding Box UI Elements
Jonathan LeBlanc
 
Understanding Box applications, tokens, and scoping
Jonathan LeBlanc
 
The Future of Online Money: Creating Secure Payments Globally
Jonathan LeBlanc
 
Creating an In-Aisle Purchasing System from Scratch
Jonathan LeBlanc
 
Secure Payments Over Mixed Communication Media
Jonathan LeBlanc
 
Protecting the Future of Mobile Payments
Jonathan LeBlanc
 
Node.js Authentication and Data Security
Jonathan LeBlanc
 
PHP Identity and Data Security
Jonathan LeBlanc
 
Secure Payments Over Mixed Communication Media
Jonathan LeBlanc
 
Protecting the Future of Mobile Payments
Jonathan LeBlanc
 
Future of Identity, Data, and Wearable Security
Jonathan LeBlanc
 
Kill All Passwords
Jonathan LeBlanc
 
Ad

Recently uploaded (20)

PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Digital Circuits, important subject in CS
contactparinay1
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 

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!