-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslides.html
589 lines (391 loc) · 13.5 KB
/
slides.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Speacker Description</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
h1, h2, h3 {
font-weight: 400;
margin-bottom: 0;
}
.remark-slide-content h1 { font-size: 3em; }
.remark-slide-content h2 { font-size: 2em; }
.remark-slide-content h3 { font-size: 1.6em; }
.footnote {
position: absolute;
bottom: 3em;
}
li p { line-height: 1.25em; }
.red { color: #fa0000; }
.large { font-size: 2em; }
a, a > code {
color: rgb(249, 38, 114);
text-decoration: none;
}
code {
background: none repeat scroll 0 0 #F8F8FF;
border: 1px solid #DEDEDE;
border-radius: 3px ;
padding: 0 0.2em;
}
.remark-code, .remark-inline-code { font-family: "Bitstream Vera Sans Mono", "Courier", monospace; }
.remark-code-line-highlighted { background-color: #373832; }
.pull-left {
float: left;
width: 47%;
}
.pull-right {
float: right;
width: 47%;
}
.pull-right ~ p {
clear: both;
}
#slideshow .slide .content code {
font-size: 0.8em;
}
#slideshow .slide .content pre code {
font-size: 0.9em;
padding: 15px;
}
.main-title, .title {
background: #272822;
color: #777872;
text-shadow: 0 0 20px #333;
}
.title h1, .title h2, .main-title h1, .main-title h2 {
color: #f3f3f3;
line-height: 0.8em;
}
/* Custom */
.remark-code {
display: block;
padding: 0.5em;
}
</style>
</head>
<body>
<textarea id="source">
class: middle, center
#Token Based Authentication system using JWT
By Jaysinh Shukla
---
### Speacker Description
.center[![Speaker Image](images/jaysinh_shukla.jpg)]
* **Role:** Fullstack developer
* **Github:**
1 http://github.com/ultimatecoder
2 http://github.com/jsh-odoo
* **Twitter:** [@jaysinhp](https://twitter.com/jaysinhp)
* **Emai:** [[email protected]](mailto:[email protected])
* **IRC:** thebigj
---
## Types of Authentication
* **Session / Cookie Authentication**
* **Token Authentication**
---
background-image: url(images/session_authentication_multiple_user.svg)
### Session Authentication for Multiple User
---
### Session or Cookie Authentication
* Client sends authentication credentials (username and password) to Server.
* Server verifies authentication credentials
* if valid, assigns **session storage**, creates **session id** and returns
session id to requested client.
* Client stores **session id** probably at **Cookie** storage. This id
is sent by client with every request. And from that **session id** user is
identified further.
* This allows to identified the same user from upcoming request without
reasking user credentials.
---
### Disadvantages of Session Authentication
* Difficult to handle with
[Load balancer][1]
* Required high amount of resource(RAM without mass-storage) for maintaining
huge amount of user session parallaly.
[1]: https://en.wikipedia.org/wiki/Load_balancing_(computing)
* [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
doesn't work well with cookies
---
### Birth of Token Authentication
* Token based authentication are most popular authentication system for APIs.
* Comparatively puts less load than **Session authentication**.
* Best for
* Scaling
* Load balancer
* No **cookie**, No [CSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)
protection.
* Same API, Authentication will be used for Mobile and Front end app.
---
### Algorithm of Token Authentication
* Client sends authentication credentials.
* Authentication credentials are varified by server. If valid **Token** is
crated.
* **Token** is logged to database and the token is sent back as
**authentication token**
* The client sends **Token** with every request to get verified.
* Normally token is generated with random value and hashed with popular
hashing algorithm.
* Revoking access of specific **Token** by deactivating record at token
table.
---
background-image: url(images/Normal_token_authentication.svg)
---
### Example of authentication at Djnago Rest Framework
```python
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=...)
print token.key
```
Above code is used at authentication view where that **token.key** is returned
if credentials are right.
Assuming random output **9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b**
**Example of Client request using [curl](https://curl.haxx.se/)**
```bash
curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'
```
---
### Example of Token Authentication at Django Rest Framework
```python
@python_2_unicode_compatible
class Token(models.Model):
"""
The default authorization token model.
"""
key = models.CharField(_("Key"), max_length=40, primary_key=True)
user = models.OneToOneField(
settings.AUTH_USER_MODEL, related_name='auth_token',
on_delete=models.CASCADE, verbose_name=_("User")
)
created = models.DateTimeField(_("Created"), auto_now_add=True)
class Meta:
verbose_name = _("Token")
verbose_name_plural = _("Tokens")
def save(self, *args, **kwargs):
if not self.key:
self.key = self.generate_key()
return super(Token, self).save(*args, **kwargs)
def generate_key(self):
return binascii.hexlify(os.urandom(20)).decode()
```
---
### Problems, Problems every where
* Impossible to
* identify user from which client (like Angular App, Android App, etc) is
authenticated with.
* provide way of access control with respect to client.
* judge that the token is valid by time or not.
* predict for how much time **token** is valid for.
* Difficult to
* Scale because of having dependancy on database to authenticate client
with each request
* run authentication logic seperate from API server.
* Quite difficult to
* scale
* identify when client is identified from multiple sources symentically.
---
### Solution is awesome JWT!
* Suggested pronunciation is "jot".
* JSON Web Token is JSON based Web Authentication Token.
* The token is a combination of three parts. Header, Claim set and Signature.
* Each part of authentication token is encoded with
[base64url](https://en.wikipedia.org/wiki/Base64) encoding and seperated with **"."**
---
background-image: url(images/JWT_token_authentication.svg)
---
### Structure Of JSON Web Token
```base
eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4
MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K2
7uhbUJU1p1r_wW1gFWFOEjXk
```
* The token is containing three different part seperated with **"."**
* Each part is encoded with [base64url](https://en.wikipedia.org/wiki/Base64) encoding.
* The first part the .red[Red Part] is **JOSE Header**
* The second part the .blue[Blue Part] is **JWT Claim set**
* The third part the .green[Green Part] is **JWT Signature**
* **Base64URL(JOSE Header).Base64URL(JWT Claims).Base64URL(JWT Signatuer)**
---
### JOSE Header
```base
eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9
```
* Decoded with Base64 encoding:
```json
{
"typ":"JWT",
"alg":"HS256"
}
```
* Here,
* **typ** defines type of the JSON Web Token. It is not optional.
* **alg** represents type of algorithm used for signing the claim set.
---
### JWT Claim-set
```bash
eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ
```
* Decoding with Base64 encoding:
```json
{
"iss":"joe",
"exp":1300819380,
"is_root":true
}
```
* Here,
* **iss** is registered claim. It represents the name of Issuer of the token
* **exp** is registered claim. It represents expiration time in format of
[Unix time](https://en.wikipedia.org/wiki/Unix_time)
* **is_root** is unregistred claim. User defined claim which can be presumed
that it is considring user as root user.
---
### JWT Signature
```bash
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
```
* Signature is MAC of encoded JOSE Header and encoded JWS Payload
with the HMAC SHA-256 algorithm.
* And then base64url encoding of that HMAC value.
* This signature helps to verify the authenticity of the **Token**.
---
### Generate JWT Token
* Define **secret key**
* Example using [pyjwt](https://github.com/jpadilla/pyjwt)
```python
>>> import jwt
>>> token = jwt.encode({'user_id': 1}, '12345', algorithm='HS256')
>>> token
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.0X_1nSfbSETzHhcoeywtv6zXXlQd13M3d0-su89rfvM'
```
* Here, **12345** is considered as secret key and **HS256** is the algorithm
we are using.
---
### Example of Verifying Token
```python
# Assume token is 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.0X_1nSfbSETzHhcoeywtv6zXXlQd13M3d0-su89rfvM'
>>> jwt.decode(token, '12345', algorithms=['HS256'])
{'user_id': 1}
```
* Here, **12345** is secret key.
---
### JWT Authentication at Django
```python
from django.contrib.auth import authenticate
class Login(View):
def post(self, request, *args, **kwargs):
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
payload = {
'id': user.pk,
'username': user.username,
'staff': user.is_staff,
'exp': datetime.utcnow() + EXPIRY_TIME
}
token = {'token': jwt.encode(payload, SECRET)}
return HttpResponse(
json.dumps(token),
content_type="application/json"
)
else:
return HttpResponse(
json.dumps({'Error': "Invalid credentials"}),
status=400,
content_type="application/json"
)
```
---
### JWT Token Verification at Django
```python
class JWT_AuthMiddleware(object):
def _get_token(request=None):
return request.META.get('HTTP_AUTHORIZATION') or request.GET.get('token')
def process_request(self, request):
token = self._get_token(request)
try:
payload = jwt.decode(token, SECRET)
request.user = User.objects.get(
username=payload.get('username'),
pk=payload.get('id'),
is_active=True
)
except jwt.ExpiredSignature, jwt.DecodeError, jwt.InvalidTokenError:
return HttpResponse({'Error': "Token is invalid"}, status="403")
except User.DoesNotExist:
return HttpResponse({'Error': "Internal server error"}, status="500")
```
---
### Still it is not over!
* If user is logged out, then also the token will be accepted until it is
expired by time.
* For Example, We assigned the token to "X" user and assigned the expire time
to next 3 days and user is logged out after 1 day, that token can be
used by attacker for that unused 2 days and API will consider **Token** as
valid.
* As a best practice, set expiry time not longer than **10 minutes**!
* As a good practice keep less values in claim. Adding many claims may
increase size of token which takes time to transfer the token.
* Change your **Secret key** periodically and Black list tokens if possible.
---
### What we are doing with JWT
* Creating JWT token
* Validating **Token** at every request.
* Allowing user to **refresh token** if given **Token** is valid.
* If user is logging out then creating entry of token to **Black list** table
* Advantage:
* Token will not be used further if it is **Black listed** even in the
valid time frame.
---
background-image: url(images/Our_token_authentication.svg)
---
### JWT Claims
* Types of Claims
1 Registered Claim Names
2 Public Claim Names
3 Private Claim Names
---
### JWT Registered Claim names
* **iss:** Dipicting Issuer of the token
* **sub:** Subject of the Token
* **aud:** Audiance for which token is given for
* **exp:** Expiration time in Unix time.
* **nbf:** Token should not be accepted before this value. In Unix time format
* **iat:** Representing age of the token
* **jti:** Dipicting ID of the token
---
### JWT Public Claim names
* It can be defined by fellows using JWT on condition that they have to
register this claim at [IANA "JSON Web Token Claims" registry](http://www.iana.org/assignments/jwt/jwt.xhtml)
---
### JWT Private Claim names
* Custom claims which are not publicly used but represented as claims in JWT.
* This custom claims should be considered as private claims.
---
### Similar Technologies
1 [Simple Web Token](https://msdn.microsoft.com/library/azure/hh781551.aspx)
2 [JSON Simple Singh](https://jsonenc.info/jss/1.0/)
---
### Why not to go with Oauth 2.0?
* Oauth 2.0 uses JWT as token exchange standard.
* But Oauth 2.0 is more focused for three parties. **Resource owner**, **Authorization Server**,
**Resource Server**
* Using JWT is simple and more efficient when focus is only authentication.
* OAuth 2.0 contains many payload values which will increase the size of token.
---
### References
* https://en.wikipedia.org/wiki/Session_(computer_science)
* https://tools.ietf.org/html/rfc7519
* https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
</textarea>
<script src="http://gnab.github.io/remark/downloads/remark-latest.min.js"></script>
<script>
var slideshow = remark.create();
</script>
<script></script>
</body>
</html>