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
110
Surrounded by Microservices
damirsvrtan
2
5k
Building Serverless Ruby Bots @ Ruby Conf 2018
damirsvrtan
0
360
Building Serverless Ruby Bots @ Paris.rb Conf 2018
damirsvrtan
1
2k
Importing and serving millions of records
damirsvrtan
1
120
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
Importmapを使ったJavaScriptの 読み込みとブラウザアドオンの影響
swamp09
4
1.2k
プロジェクト新規参入者のリードタイム短縮の観点から見る、品質の高いコードとアーキテクチャを保つメリット
d_endo
1
1k
Dev ContainersとGitHub Codespacesの素敵な関係
ymd65536
1
120
Honoの来た道とこれから
yusukebe
19
3k
推し活の ハイトラフィックに立ち向かう Railsとアーキテクチャ - Kaigi on Rails 2024
falcon8823
6
2.1k
Universal Linksの実装方法と陥りがちな罠
kaitokudou
1
220
Content Security Policy入門 セキュリティ設定と 違反レポートのはじめ方 / Introduction to Content Security Policy Getting Started with Security Configuration and Violation Reporting
uskey512
1
420
約9000個の自動テストの 時間を50分->10分に短縮 Flakyテストを1%以下に抑えた話
hatsu38
23
10k
Nuxt UI Pro、NuxtHub、Nuxt Scripts、Nuxtエコシステムをふんだんに利用して開発するコーポレートサイト@Vue Fes Japan 2024
shingangan
3
880
RailsのPull requestsのレビューの時に私が考えていること
yahonda
5
1.7k
PHP でアセンブリ言語のように書く技術
memory1994
PRO
1
150
gopls を改造したら開発生産性が高まった
satorunooshie
8
240
Featured
See All Featured
Documentation Writing (for coders)
carmenintech
65
4.4k
The Cost Of JavaScript in 2023
addyosmani
45
6.6k
Scaling GitHub
holman
458
140k
Embracing the Ebb and Flow
colly
84
4.4k
How to train your dragon (web standard)
notwaldorf
88
5.7k
GraphQLとの向き合い方2022年版
quramy
43
13k
Building Better People: How to give real-time feedback that sticks.
wjessup
363
19k
Happy Clients
brianwarren
97
6.7k
Facilitating Awesome Meetings
lara
49
6k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
664
120k
Thoughts on Productivity
jonyablonski
67
4.3k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
328
21k
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