Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Stateless authentication w/ JSON Web Tokens
Search
DamirSvrtan
October 06, 2017
Programming
5
280
Stateless authentication w/ JSON Web Tokens
DamirSvrtan
October 06, 2017
Tweet
Share
More Decks by DamirSvrtan
See All by DamirSvrtan
Designing APIs: Less Data is More
damirsvrtan
1
430
Crossing Domain Boundaries with GraphQL
damirsvrtan
0
120
Surrounded by Microservices
damirsvrtan
2
5.1k
Building Serverless Ruby Bots @ Ruby Conf 2018
damirsvrtan
0
370
Building Serverless Ruby Bots @ Paris.rb Conf 2018
damirsvrtan
1
2k
Importing and serving millions of records
damirsvrtan
1
130
Building Ruby Bots on AWS Lambda
damirsvrtan
0
1.1k
Reinventing The Bootcamp Idea
damirsvrtan
0
160
JSON Web Tokens
damirsvrtan
0
180
Other Decks in Programming
See All in Programming
17年周年のWebアプリケーションにTanStack Queryを導入する / Implementing TanStack Query in a 17th Anniversary Web Application
saitolume
0
250
rails statsで大解剖 🔍 “B/43流” のRailsの育て方を歴史とともに振り返ります
shoheimitani
2
930
モバイルアプリにおける自動テストの導入戦略
ostk0069
0
110
ブラウザ単体でmp4書き出すまで - muddy-web - 2024-12
yue4u
2
460
なまけものオバケたち -PHP 8.4 に入った新機能の紹介-
tanakahisateru
1
120
htmxって知っていますか?次世代のHTML
hiro_ghap1
0
330
return文におけるstd::moveについて
onihusube
1
730
StarlingMonkeyを触ってみた話 - 2024冬
syumai
3
270
Jakarta EE meets AI
ivargrimstad
0
230
rails stats で紐解く ANDPAD のイマを支える技術たち
andpad
1
290
layerx_20241129.pdf
kyoheig3
2
290
第5回日本眼科AI学会総会_AIコンテスト_3位解法
neilsaw
0
170
Featured
See All Featured
Statistics for Hackers
jakevdp
796
220k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
29
2k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.9k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
280
13k
The Invisible Side of Design
smashingmag
298
50k
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
356
29k
How To Stay Up To Date on Web Technology
chriscoyier
789
250k
CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again
sstephenson
159
15k
GitHub's CSS Performance
jonrohan
1030
460k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
48k
Designing for Performance
lara
604
68k
How to train your dragon (web standard)
notwaldorf
88
5.7k
Transcript
Authentication with JSON Web Tokens
01 API AUTHENTICATION
CLIENT SERVER
[email protected]
&PASSWORD=PASS123 AUTH_TOKEN=RAND0M$TR1N6
CLIENT SERVER ARTICLES?AUTH_TOKEN=RAND0M$TR1N6
02 SINGLE AUTH TOKEN PER USER
id email password_digest auth_token 1
[email protected]
$2a$10$5FkD.. 23ZS921a USERS TABLE
GENERATE A RANDOM AUTH TOKEN class User before_save :generate_auth_token def
generate_auth_token loop do self.auth_token = Devise.friendly_token break if User.find_by_auth_token(auth_token).nil? end end end
PROBLEMS WITH THE SINGLE AUTH TOKEN APPROACH
NAIVE IMPLEMENTATIONS NEVER EXPIRE THEM
STORING IT IN PLAIN TEXT
ISN’T THAT THE SAME AS STORING PASSWORDS IN PLAIN TEXT?
NOT QUITE
• difficult to change • used across several services PASSWORDS
• easy to change • auto-generated, random, unique • not
used across several services AUTH TOKENS
03 SINGLE HASHED AUTH TOKEN PER USER
NOT STORING IT IN PLAIN TEXT
BROWSER SERVER EM AIL=DAM IR@ EXAM PLE.COM &PASSW ORD=PASS123 AUTH_TOKEN=RAND0M
$TR1N6 EM AIL=DAM IR@ EXAM PLE.COM &PASSW ORD=PASS123 MOBILE AUTH_TOKEN=ANOTHER-RAND0M $TR1N6
04 MULTIPLE HASHED AUTH TOKENS PER USER
user_id token_digest 1 $2a$10$5FkD.. 2 $3R$D9S21$.. 1 $23$2sBPSA.. AUTH TOKENS
TABLE
ERASE TOKENS PERIODICALLY
0Rel STORE TOKENS NOWHERE WHAT IF WE DIDN’T STORE THEM
ANYWHERE?
LET’S DO SOMETHING SIMILAR TO RAILS SESSIONS!
05 RAILS SESSION STORAGE
CLIENT SERVER
[email protected]
&PASSWORD=PASS123 SET-COOKIE: APP_SESSION=23OFSKL932RDASDAFSFJ23
session[:user_id] = current_user.id
sign(encrypt(hash))
CLIENT SERVER APP_SESSION=23OFSKL932RDASDAFSFJ23
decrypt(verify_signature(cookie))
User.find(session[:user_id])
WE COULD DO SOMETHING SIMILAR… … OR FOLLOW AN OPEN
STANDARD
06 JSON WEB TOKENS
JSON Web Tokens are an open standard that defines a
compact and self-contained way to securely share information between parties as a JSON Object.
CLIENT SERVER
[email protected]
&PASSWORD=PASS123 AUTH_TOKEN=33WE.DAS3Q.ADAS
TO THE API CONSUMER IT CAN LOOK RANDOM..
..BUT IT’S MUCH MORE
IT STORES INFORMATION INSIDE OF IT.
DATA + SIGNATURE
DATA + SIGNATURE data = { "user_id": 231 } token
= data + sign(data)
ABASASD.U93RJADSF.ASASD
ABASASD.U93RJADSF.ASASD HEADER.PAYLOAD.SIGNATURE
THE JWT HEADER
{ "typ": "JWT", "alg": "HS256" } HEADER
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 BASE64 ENCODED HEADER
THE JWT BODY
{ “user_id": 231, "exp": 1300819380, } BODY
eyJpc3MiOiJzY290Y2guaW8iLCJleHAiOjE BASE64 ENCODED BODY
THE JWT SIGNATURE
encoded_string = Base64.encode64(header) + "." + Base64.encode64(payload); OpenSSL::HMAC.hexdigest( OpenSSL::Digest.new(‘sha256'), Rails.application.secrets.secret_key_base,
encoded_string ) GENERATE A SIGNATURE
SIGNATURE 03f329983b86f7d9a9f5fef85305880101d
JSON WEB TOKEN eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e yJpc3MiOiJzY290Y2guaW8iLCJleHAiOjE. 03f329983b86f7d9a9f5fef85305880101d
iss: The issuer of the token sub: The subject of
the token exp: This will define the expiration in NumericDate value. nbf: Defines the time before which the JWT MUST NOT be accepted for processing iat: The time the JWT was issued. Can be used to determine the age of the JWT BODY CLAIMS
08 JWT <> RAILS SESSIONS
RAILS SESSIONS ARE ENCRYPTED JWT’S ARE SIGNED
RAILS SESSIONS CAN’T BE READ ON THE CLIENT SIDE JWT’S
CAN BE READ ON THE CLIENT SIDE
SECRET INFORMATION IN JWT’S MUST BE EXPLICITLY ENCRYPTED
09 STATELESS AUTH
{ “user_id": 231 } BODY
FORCE LOGOUT / ACCOUNT HIJACKING
10 REVOCATION
HOW DOES DEVISE HANDLE THIS?
INSERT A PART OF THE USERS PASSWORD HASH INTO THE
PAYLOAD
SESSION['WARDEN.USER.KEY'] [[1], "$2A$11$NNJPSD1Q36CG.PSQKPBU/U"]
{ "exp": 1300819380, “user_id": 1, “pwd_start": $2a$11$nnjPSD1q36Cg.PSqKPBU }
DISABLE TOKENS WITH AN IAT CLAIM OLDER THAN 6.10.2017
{ “user_id": 231, "exp": 1300819380, "iat": 1300700011, } BODY
id email password min_issued_at 1
[email protected]
$2a$10$5FkD.. 2017-09-09 08:59:06.750087
JTI JSON TOKEN IDENTIFIER
{ "exp": 1300819380, "jti": 0A212BXC12, } BODY
id email password jti 1
[email protected]
$2a$10$5FkD.. DSAY039R21S
LOGOUTS DON’T INVALIDATE TOKENS
10 JWT ADVANTAGES
SAFELY SHARE DATA WITH THE CLIENT APP
{ “user_id": 231, "admin": true, “permissions”: [‘read’, ‘write’] }
SELF CONTAINED TIME-BASED EXPIRATION HANDLING
SCALABILITY
MICROSERVICES INFORMATION SHARING
NOT REINVENTING THE WHEEL - USING AN OPEN STANDARD.
LANGUAGE SUPPORT
JWT.IO RUBY, ELIXIR, GO, PYTHON, JAVA, RUST..
11 RAILS IMPLEMENTATIONS
None
None
None
CONCLUSIONS
SCALABILITY. SIMPLICITY. STANDARDIZATION.
ALWAYS IMPLEMENT A REVOCATION TECHNIQUE
NO SILVER BULLET.
None
Damir Svrtan Rails Team Lead @ infinum.co Organizer @ Ruby
Zagreb Hit me up on twitter @DamirSvrtan