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
170
JSON Web Tokens
damirsvrtan
0
180
Other Decks in Programming
See All in Programming
Monixと常駐プログラムの勘どころ / Scalaわいわい勉強会 #4
stoneream
0
280
アクターシステムに頼らずEvent Sourcingする方法について
j5ik2o
4
260
RWC 2024 DICOM & ISO/IEC 2022
m_seki
0
210
【re:Growth 2024】 Aurora DSQL をちゃんと話します!
maroon1st
0
770
php-conference-japan-2024
tasuku43
0
270
testcontainers のススメ
sgash708
1
120
責務を分離するための例外設計 - PHPカンファレンス 2024
kajitack
2
680
Cloudflare MCP ServerでClaude Desktop からWeb APIを構築
kutakutat
1
540
見えないメモリを観測する: PHP 8.4 `pg_result_memory_size()` とSQL結果のメモリ管理
kentaroutakeda
0
330
선언형 UI에서의 상태관리
l2hyunwoo
0
160
ゆるやかにgolangci-lintのルールを強くする / Kyoto.go #56
utgwkk
2
380
nekko cloudにおけるProxmox VE利用事例
irumaru
3
430
Featured
See All Featured
Building a Modern Day E-commerce SEO Strategy
aleyda
38
7k
A Modern Web Designer's Workflow
chriscoyier
693
190k
A designer walks into a library…
pauljervisheath
204
24k
Raft: Consensus for Rubyists
vanstee
137
6.7k
A Tale of Four Properties
chriscoyier
157
23k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
38
1.9k
How to Ace a Technical Interview
jacobian
276
23k
Building a Scalable Design System with Sketch
lauravandoore
460
33k
Into the Great Unknown - MozCon
thekraken
33
1.5k
Documentation Writing (for coders)
carmenintech
66
4.5k
Music & Morning Musume
bryan
46
6.2k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
48k
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