SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Authentication
with JSON Web Tokens
2016. 06. 04
pyconTW
Shuhsi Lin
Data Engineer of Throughtek
JSON Web Tokens
2
JWT
“jot”
3
1. Why we need authorization
2. The idea of Authorization Server
3. How to implement JWT
- PyJWT
- Django & Flask
4
Agenda
About Me
Data Engineer of Throughtek
Currently working with
- IoT -PaaS
- Streaming processing framework
- WebAPI
- Lurking in PyHug, Taipei.py and various Meetups
5
Shuhsi Lin
sucitw@gmail.com
shuhsi_lin@tutk.com
I A A
Identity
“Who are you?”
6
Authentication
“OK, how can you prove it?”
Authorization
“What can you do?”
Identity and Access Management (IAM)
Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 7
• Generic applications
• Customization service
• Kalay Kit
• FW integration
micro-service system
Turnkey Solution for Rapid IoT Deployment
Kalay Platform
What is Kalay?
9
Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 10 10
“Handshake” in the language
of the aboriginal Tao people of Taiwan
Connecting All Devices
Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 11
User Account
• Define multiple user types
• Manage and control user permission
• Monitor login status and activity
UID & Device
• Real time log analysis
• Track connection status, IP, region
• Monitor and backup log data
Why we need Identity Management
(Device and User Account)
A server has to know
who is requesting the resource
12
How has authentication been done in web?
13
● Server based
● Token based
Server based authentication
14
user id/password
Problems from Server based authentication
● Sessions
● Scalability
● Cross-Origin Resource Sharing (CORS)
● Cross-Site Request Forgery (CSRF)
15
Token based authentication
16
user id/password
Stateless
Token based authentication
● Stateless and scalable servers
● Mobile application ready
● Pass authentication to other applications
● Extra security
17
18
https://jwt.io/
2,506 6,120
https://github.com/search?q=jwt
http://stackoverflow.com/search?q=jwt
● Compact and Self-contained
● Across different programming languages
● Passed around easily
JWT looks like?
19
Three strings separated by “.”
aaaaaaaaa.bbbbbbbbb.ccccccccccc
header payload signature
20
https://jwt.io/#debugger-io
don’t put sensitive data here
How usually JSON Web Tokens work ?
21
How usually JSON Web Tokens work ?
22
POST login/
user id/password
https://auth0.com/learn/json-web-tokens/
return JWT token
request with Header
Authorization: Bearer <json web token>
create JWT
Check JWT
send responses
What do we put in payload
● Reserved : predefined claim
● iss (issuer), exp (expiration time), sub (subject), aud (audience)
● and etc.
● Public:
● name, email, email_verified, and etc.
● http://www.iana.org/assignments/jwt/jwt.xhtml
● Private : custom claims
23
How to implement it in
python ?
24
25
In [1]: import json
In [2]: import hmac
In [3]: from hashlib import sha256
In [4]: from base64 import urlsafe_b64encode
In [5]: segments =[]
In [6]: header_dict = {
...: 'typ': 'JWT',
...: 'alg': 'HS256'
...: }
In [7]: json_header = json.dumps(header_dict).encode('utf-8')
In [8]: header = urlsafe_b64encode(json_header)
In [9]: segments.append(header)
In [10]: segments
Out[10]: [b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9']
26
In [11]: payload_dict = {
....: 'user_id':'pythontw2016'
....: }
In [12]: json_payload =json.dumps(payload_dict).encode('utf-8')
In [13]: payload = urlsafe_b64encode(json_payload)
In [14]: segments.append(payload)
In [15]: segments
Out[15]:
[b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9',
b'eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9']
27
In [16]: SECRET = b'secret'
In [17]: signing_input = b'.'.join(segments)
In [18]: sig = hmac.new (SECRET, signing_input, sha256)
In [19]: signature = urlsafe_b64encode(sig.digest())
In [20]: segments.append(signature)
In [21]: segments
Out[21]:
[b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9',
b'eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9',
b'qhevGfl16LBHjRG2wb6xDitbGt3lDK-2iUYCsLseCJY=']
In [22]: token = b'.'.join(segments)
In [23]: token
Out[23]: b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9.
eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9.qhevGfl16LBHjRG2wb6xDitbGt3lDK-
2iUYCsLseCJY='
Test this token in https://jwt.io/
We don’t need to
reinvent the
wheel
28
29
https://jwt.io/#libraries-io
PyJWT
30
PyJWT
Django DRF JWT Auth
json
hmac
base64
hashlib
Flask-JWT
PyJWT
>>> import jwt
>>> jwt_token = jwt.encode({ 'payload': ‘pycontw 2106’ }, 'secret',
algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJwYXlsb2FkIjoicHljb250dyAyMDE2In0.
TRRENrqd8lc3_AQeo3IRheVkZpMkcqXqYQi891pFL6w’
>>> jwt.decode(jwt_token, 'secret', algorithms=[ 'HS256'])
{'payload': 'pycontw 2016'}
31
https://github.com/jpadilla/pyjwt
pip install PyJWT
see more in Registered Claim Names
Example Scenarios
32
Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 33
• Generic applications
• Customization service
• Kalay Kit
• FW integration
micro-service system
Kalay
services
Users
Kalay AM Kalay DM
JWT
login
Kalay DC
mqtt/https
shared keys shared keys
shared keys
Kalay Cloud
Kalay
services
Kalay
services
devices
actions
(bind/view/control….)
with JWT
Messaging API for Mobile Apps and Websites
● http://api.diuit.com/
Authentication with JWT for security purpose
1. User sends login request with credential
2. Auth user on your server (account server)
3. Request for Nonce on Diuit server
4. Obtain nonce from Diuit server
5. Use JWT to request session token
6. Obtain session token from Diuit server
7. Send session token back to messaging client
8. Authenticate messaging client on Diuit server using
"loginWithAuthToken"
JWT
Your own account server
user login
nonce
=>create JWT
{ "typ": "JWT", "alg": "RS256" "cty": "diuit-eit;v=1"
"kid": ${EncryptionKeyId} }
header
{ "iss": ${DIUIT_APP_ID}
"sub": ${UNIQUE_USER_ID}
"iat": ${CURRENT_TIME_IN_ISO8601_FORMAT}
"exp":${SESSION_EXPIRATION_TIME_IN_ISO8601_FORMAT}
"nce": ${AUTHENTICATION_NONCE} }
payload
Django REST framework JWT
JSON Web Token Authentication support for Django REST Framework
37
Django DRF JWT
38
https://github.com/GetBlimp/django-rest-framework-jwt
Steps:
● pip install djangorestframework-jwt
● add JSONWebTokenAuthentication in Django REST framework's
DEFAULT_AUTHENTICATION_CLASSES (settings.py)
● add URL routes (urls.py)
○ provide JWT token (obtain_jwt_token)
○ refresh token (refresh_jwt_token)
○ verify token (verify_jwt_token)
● additional settings
Requirements
● Python (2.7, 3.3, 3.4)
● Django (1.8, 1.9)
● Django REST Framework (3.0, 3.1, 3.2, 3.3)
settings.py
39
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
from rest_framework_jwt.views import obtain_jwt_token
#...
urlpatterns = patterns(
'',
# ...
url(r'^api-token-auth/', obtain_jwt_token),
url(r'^api-token-refresh/', refresh_jwt_token),
url(r'^api-token-verify/', verify_jwt_token),
)
urls.py
http://getblimp.github.io/django-rest-framework-jwt/
Flask-JWT
Add basic JWT features to your Flask application
40
https://pythonhosted.org/Flask-JWT/
Flask-JWT
from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp
41
https://pythonhosted.org/Flask-JWT/
pip install Flask-JWT
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
users = [
User(1, 'user1', 'abcxyz'),
User(2, 'user2', 'abcxyz'),
]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
Minimum viable application configuration:
42
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = ' super-secret'
jwt = JWT(app, authenticate, identity )
def identity(payload):
user_id = payload['identity']
return userid_table.get(user_id,
None)
def authenticate(username, password):
user = username_table.get(username, None)
if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
return user
@app.route('/protected')
@jwt_required()
def protected():
return '%s' % current_identity
if __name__ == '__main__':
app.run()
Configuration
JWT_AUTH_URL_RULE:
The authentication endpoint URL.
Defaults to /auth
https://pythonhosted.org/Flask-JWT/
jwt working
Recap
● JWT (‘jot’) : header, payload, signature
● Stateless token-based authentication
● Use libraries
● PyJWT, Django DRF JWT , Flask-JWT
● Provide, refresh, verify JWT
43
About JWT
Ref:
● JWT
● https://jwt.io/
● https://auth0.com/learn/json-web-tokens/
● https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html
● PyJWT (https://pyjwt.readthedocs.org/)
● django-rest-framework-jwt (http://getblimp.github.io/django-rest-framework-jwt/)
● Flask-JWT (https://pythonhosted.org/Flask-JWT/)
● DjangoCon US 2014 talk on JWT https://speakerdeck.com/jpadilla/djangocon-json-web-tokens
● JWT in Auth0 https://auth0.com/blog/2014/12/02/using-json-web-tokens-as-api-keys/
About Authentication
● https://www.owasp.org/index.php/Authentication_Cheat_Sheet
and others:
● Kalay platform (http://www.throughtek.com.tw/kalay_overview.html)
● diuit messaging api (http://api.diuit.com/ , https://github.com/diuitAPI)
● icons: (https://thenounproject.com/)
44
Thank you!
Questions?
45

Contenu connexe

Tendances

What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017Matt Raible
 
Micro Web Service - Slim and JWT
Micro Web Service - Slim and JWTMicro Web Service - Slim and JWT
Micro Web Service - Slim and JWTTuyen Vuong
 
Stateless authentication for microservices
Stateless authentication for microservicesStateless authentication for microservices
Stateless authentication for microservicesAlvaro Sanchez-Mariscal
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsrobertjd
 
Single-Page-Application & REST security
Single-Page-Application & REST securitySingle-Page-Application & REST security
Single-Page-Application & REST securityIgor Bossenko
 
Stateless authentication for microservices - Spring I/O 2015
Stateless authentication for microservices  - Spring I/O 2015Stateless authentication for microservices  - Spring I/O 2015
Stateless authentication for microservices - Spring I/O 2015Alvaro Sanchez-Mariscal
 
An Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldAn Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldVMware Tanzu
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinJava User Group Latvia
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2Rodrigo Cândido da Silva
 
Stateless token-based authentication for pure front-end applications
Stateless token-based authentication for pure front-end applicationsStateless token-based authentication for pure front-end applications
Stateless token-based authentication for pure front-end applicationsAlvaro Sanchez-Mariscal
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensJonathan LeBlanc
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsJon Todd
 
JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2Rodrigo Cândido da Silva
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationErick Belluci Tedeschi
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongDerek Perkins
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectSecuring RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectJonathan LeBlanc
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and PracticesPrabath Siriwardena
 
What are JSON Web Tokens and Why Should I Care?
What are JSON Web Tokens and Why Should I Care?What are JSON Web Tokens and Why Should I Care?
What are JSON Web Tokens and Why Should I Care?Derek Edwards
 

Tendances (20)

What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017
 
Micro Web Service - Slim and JWT
Micro Web Service - Slim and JWTMicro Web Service - Slim and JWT
Micro Web Service - Slim and JWT
 
Stateless authentication for microservices
Stateless authentication for microservicesStateless authentication for microservices
Stateless authentication for microservices
 
Building Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTsBuilding Secure User Interfaces With JWTs
Building Secure User Interfaces With JWTs
 
Single-Page-Application & REST security
Single-Page-Application & REST securitySingle-Page-Application & REST security
Single-Page-Application & REST security
 
Stateless authentication for microservices - Spring I/O 2015
Stateless authentication for microservices  - Spring I/O 2015Stateless authentication for microservices  - Spring I/O 2015
Stateless authentication for microservices - Spring I/O 2015
 
An Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices WorldAn Authentication and Authorization Architecture for a Microservices World
An Authentication and Authorization Architecture for a Microservices World
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
 
ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2ConFoo 2015 - Securing RESTful resources with OAuth2
ConFoo 2015 - Securing RESTful resources with OAuth2
 
Stateless token-based authentication for pure front-end applications
Stateless token-based authentication for pure front-end applicationsStateless token-based authentication for pure front-end applications
Stateless token-based authentication for pure front-end applications
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
JSON Web Token
JSON Web TokenJSON Web Token
JSON Web Token
 
JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2JavaOne 2014 - Securing RESTful Resources with OAuth2
JavaOne 2014 - Securing RESTful Resources with OAuth2
 
RoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs AuthorizationRoadSec 2017 - Trilha AppSec - APIs Authorization
RoadSec 2017 - Trilha AppSec - APIs Authorization
 
Authentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrongAuthentication: Cookies vs JWTs and why you’re doing it wrong
Authentication: Cookies vs JWTs and why you’re doing it wrong
 
Securing RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID ConnectSecuring RESTful APIs using OAuth 2 and OpenID Connect
Securing RESTful APIs using OAuth 2 and OpenID Connect
 
API Security : Patterns and Practices
API Security : Patterns and PracticesAPI Security : Patterns and Practices
API Security : Patterns and Practices
 
What are JSON Web Tokens and Why Should I Care?
What are JSON Web Tokens and Why Should I Care?What are JSON Web Tokens and Why Should I Care?
What are JSON Web Tokens and Why Should I Care?
 

En vedette

淺談RESTful API認證 Token機制使用經驗分享
淺談RESTful API認證 Token機制使用經驗分享淺談RESTful API認證 Token機制使用經驗分享
淺談RESTful API認證 Token機制使用經驗分享Tun-Yu Chang
 
Scala & SBT Installation Guide for JCConf Taiwan
Scala & SBT Installation Guide for JCConf TaiwanScala & SBT Installation Guide for JCConf Taiwan
Scala & SBT Installation Guide for JCConf TaiwanJimin Hsieh
 
Java & JWT Stateless authentication
Java & JWT Stateless authenticationJava & JWT Stateless authentication
Java & JWT Stateless authenticationKarlo Novak
 
Product Market Fit
Product Market FitProduct Market Fit
Product Market FitYenwen Feng
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」R.O.C.Executive Yuan
 
Testing Angular 2 Applications - Rich Web 2016
Testing Angular 2 Applications - Rich Web 2016Testing Angular 2 Applications - Rich Web 2016
Testing Angular 2 Applications - Rich Web 2016Matt Raible
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Matt Raible
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationStormpath
 
Browser Security 101
Browser Security 101 Browser Security 101
Browser Security 101 Stormpath
 
漫談人工智慧:啟發自大腦科學的深度學習網路
漫談人工智慧:啟發自大腦科學的深度學習網路漫談人工智慧:啟發自大腦科學的深度學習網路
漫談人工智慧:啟發自大腦科學的深度學習網路Jason Tsai
 
用戶體驗設計,從需求到產品落地
用戶體驗設計,從需求到產品落地用戶體驗設計,從需求到產品落地
用戶體驗設計,從需求到產品落地Ivan Wei
 

En vedette (12)

淺談RESTful API認證 Token機制使用經驗分享
淺談RESTful API認證 Token機制使用經驗分享淺談RESTful API認證 Token機制使用經驗分享
淺談RESTful API認證 Token機制使用經驗分享
 
Scala & SBT Installation Guide for JCConf Taiwan
Scala & SBT Installation Guide for JCConf TaiwanScala & SBT Installation Guide for JCConf Taiwan
Scala & SBT Installation Guide for JCConf Taiwan
 
Java & JWT Stateless authentication
Java & JWT Stateless authenticationJava & JWT Stateless authentication
Java & JWT Stateless authentication
 
Product Market Fit
Product Market FitProduct Market Fit
Product Market Fit
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」
國家發展委員會:「國家發展計畫-106至109年四年計畫暨106年計畫」
 
Testing Angular 2 Applications - Rich Web 2016
Testing Angular 2 Applications - Rich Web 2016Testing Angular 2 Applications - Rich Web 2016
Testing Angular 2 Applications - Rich Web 2016
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
 
Securing Web Applications with Token Authentication
Securing Web Applications with Token AuthenticationSecuring Web Applications with Token Authentication
Securing Web Applications with Token Authentication
 
Browser Security 101
Browser Security 101 Browser Security 101
Browser Security 101
 
漫談人工智慧:啟發自大腦科學的深度學習網路
漫談人工智慧:啟發自大腦科學的深度學習網路漫談人工智慧:啟發自大腦科學的深度學習網路
漫談人工智慧:啟發自大腦科學的深度學習網路
 
用戶體驗設計,從需求到產品落地
用戶體驗設計,從需求到產品落地用戶體驗設計,從需求到產品落地
用戶體驗設計,從需求到產品落地
 

Similaire à 2016 pycontw web api authentication

iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesErick Belluci Tedeschi
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...iMasters
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"Andreas Falk
 
Nk API - examples
Nk API - examplesNk API - examples
Nk API - examplesnasza-klasa
 
OpenStack Toronto Meetup - Keystone 101
OpenStack Toronto Meetup - Keystone 101OpenStack Toronto Meetup - Keystone 101
OpenStack Toronto Meetup - Keystone 101Steve Martinelli
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationKAI CHU CHUNG
 
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenCodemotion
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
 
OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)Torsten Lodderstedt
 
Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerAnupam Gogoi
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務升煌 黃
 
OpenID Connect 4 SSI (DIFCon F2F)
OpenID Connect 4 SSI (DIFCon F2F)OpenID Connect 4 SSI (DIFCon F2F)
OpenID Connect 4 SSI (DIFCon F2F)Torsten Lodderstedt
 
Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Mediacurrent
 
CIS 2015 Session Management at Scale - Scott Tomilson & Jamshid Khosravian
CIS 2015  Session Management at Scale - Scott Tomilson & Jamshid KhosravianCIS 2015  Session Management at Scale - Scott Tomilson & Jamshid Khosravian
CIS 2015 Session Management at Scale - Scott Tomilson & Jamshid KhosravianCloudIDSummit
 
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)Scott Brady
 
Building IAM for OpenStack
Building IAM for OpenStackBuilding IAM for OpenStack
Building IAM for OpenStackSteve Martinelli
 
mDevCamp 2016 - Zingly, or how to design multi-banking app
mDevCamp 2016 - Zingly, or how to design multi-banking appmDevCamp 2016 - Zingly, or how to design multi-banking app
mDevCamp 2016 - Zingly, or how to design multi-banking appPetr Dvorak
 

Similaire à 2016 pycontw web api authentication (20)

iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
 
Nk API - examples
Nk API - examplesNk API - examples
Nk API - examples
 
OpenStack Toronto Meetup - Keystone 101
OpenStack Toronto Meetup - Keystone 101OpenStack Toronto Meetup - Keystone 101
OpenStack Toronto Meetup - Keystone 101
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
 
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
 
OpenID for SSI
OpenID for SSIOpenID for SSI
OpenID for SSI
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
Esquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdMEsquema de pasos de ejecución IdM
Esquema de pasos de ejecución IdM
 
OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)OpenID 4 Verifiable Credentials + HAIP (Update)
OpenID 4 Verifiable Credentials + HAIP (Update)
 
Microservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity ServerMicroservice Protection With WSO2 Identity Server
Microservice Protection With WSO2 Identity Server
 
使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務使用 Passkeys 打造無密碼驗證服務
使用 Passkeys 打造無密碼驗證服務
 
OpenID Connect 4 SSI (DIFCon F2F)
OpenID Connect 4 SSI (DIFCon F2F)OpenID Connect 4 SSI (DIFCon F2F)
OpenID Connect 4 SSI (DIFCon F2F)
 
Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication Using JSON Web Tokens for REST Authentication
Using JSON Web Tokens for REST Authentication
 
CIS 2015 Session Management at Scale - Scott Tomilson & Jamshid Khosravian
CIS 2015  Session Management at Scale - Scott Tomilson & Jamshid KhosravianCIS 2015  Session Management at Scale - Scott Tomilson & Jamshid Khosravian
CIS 2015 Session Management at Scale - Scott Tomilson & Jamshid Khosravian
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)
Secure Authorization for your Printer: The OAuth Device Flow (DevSum 2018)
 
Building IAM for OpenStack
Building IAM for OpenStackBuilding IAM for OpenStack
Building IAM for OpenStack
 
mDevCamp 2016 - Zingly, or how to design multi-banking app
mDevCamp 2016 - Zingly, or how to design multi-banking appmDevCamp 2016 - Zingly, or how to design multi-banking app
mDevCamp 2016 - Zingly, or how to design multi-banking app
 

Dernier

Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptJasonTagapanGulla
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 

Dernier (20)

Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
Solving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.pptSolving The Right Triangles PowerPoint 2.ppt
Solving The Right Triangles PowerPoint 2.ppt
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 

2016 pycontw web api authentication

  • 1. Authentication with JSON Web Tokens 2016. 06. 04 pyconTW Shuhsi Lin Data Engineer of Throughtek
  • 4. 1. Why we need authorization 2. The idea of Authorization Server 3. How to implement JWT - PyJWT - Django & Flask 4 Agenda
  • 5. About Me Data Engineer of Throughtek Currently working with - IoT -PaaS - Streaming processing framework - WebAPI - Lurking in PyHug, Taipei.py and various Meetups 5 Shuhsi Lin sucitw@gmail.com shuhsi_lin@tutk.com
  • 6. I A A Identity “Who are you?” 6 Authentication “OK, how can you prove it?” Authorization “What can you do?” Identity and Access Management (IAM)
  • 7. Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 7 • Generic applications • Customization service • Kalay Kit • FW integration micro-service system
  • 8. Turnkey Solution for Rapid IoT Deployment Kalay Platform
  • 10. Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 10 10 “Handshake” in the language of the aboriginal Tao people of Taiwan Connecting All Devices
  • 11. Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 11 User Account • Define multiple user types • Manage and control user permission • Monitor login status and activity UID & Device • Real time log analysis • Track connection status, IP, region • Monitor and backup log data Why we need Identity Management (Device and User Account)
  • 12. A server has to know who is requesting the resource 12
  • 13. How has authentication been done in web? 13 ● Server based ● Token based
  • 15. Problems from Server based authentication ● Sessions ● Scalability ● Cross-Origin Resource Sharing (CORS) ● Cross-Site Request Forgery (CSRF) 15
  • 16. Token based authentication 16 user id/password Stateless
  • 17. Token based authentication ● Stateless and scalable servers ● Mobile application ready ● Pass authentication to other applications ● Extra security 17
  • 18. 18 https://jwt.io/ 2,506 6,120 https://github.com/search?q=jwt http://stackoverflow.com/search?q=jwt ● Compact and Self-contained ● Across different programming languages ● Passed around easily
  • 19. JWT looks like? 19 Three strings separated by “.” aaaaaaaaa.bbbbbbbbb.ccccccccccc header payload signature
  • 21. How usually JSON Web Tokens work ? 21
  • 22. How usually JSON Web Tokens work ? 22 POST login/ user id/password https://auth0.com/learn/json-web-tokens/ return JWT token request with Header Authorization: Bearer <json web token> create JWT Check JWT send responses
  • 23. What do we put in payload ● Reserved : predefined claim ● iss (issuer), exp (expiration time), sub (subject), aud (audience) ● and etc. ● Public: ● name, email, email_verified, and etc. ● http://www.iana.org/assignments/jwt/jwt.xhtml ● Private : custom claims 23
  • 24. How to implement it in python ? 24
  • 25. 25 In [1]: import json In [2]: import hmac In [3]: from hashlib import sha256 In [4]: from base64 import urlsafe_b64encode In [5]: segments =[] In [6]: header_dict = { ...: 'typ': 'JWT', ...: 'alg': 'HS256' ...: } In [7]: json_header = json.dumps(header_dict).encode('utf-8') In [8]: header = urlsafe_b64encode(json_header) In [9]: segments.append(header) In [10]: segments Out[10]: [b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9']
  • 26. 26 In [11]: payload_dict = { ....: 'user_id':'pythontw2016' ....: } In [12]: json_payload =json.dumps(payload_dict).encode('utf-8') In [13]: payload = urlsafe_b64encode(json_payload) In [14]: segments.append(payload) In [15]: segments Out[15]: [b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9', b'eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9']
  • 27. 27 In [16]: SECRET = b'secret' In [17]: signing_input = b'.'.join(segments) In [18]: sig = hmac.new (SECRET, signing_input, sha256) In [19]: signature = urlsafe_b64encode(sig.digest()) In [20]: segments.append(signature) In [21]: segments Out[21]: [b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9', b'eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9', b'qhevGfl16LBHjRG2wb6xDitbGt3lDK-2iUYCsLseCJY='] In [22]: token = b'.'.join(segments) In [23]: token Out[23]: b'eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9. eyJ1c2VyX2lkIjogInB5dGhvbnR3MjAxNiJ9.qhevGfl16LBHjRG2wb6xDitbGt3lDK- 2iUYCsLseCJY=' Test this token in https://jwt.io/
  • 28. We don’t need to reinvent the wheel 28
  • 30. 30 PyJWT Django DRF JWT Auth json hmac base64 hashlib Flask-JWT
  • 31. PyJWT >>> import jwt >>> jwt_token = jwt.encode({ 'payload': ‘pycontw 2106’ }, 'secret', algorithm='HS256') 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. eyJwYXlsb2FkIjoicHljb250dyAyMDE2In0. TRRENrqd8lc3_AQeo3IRheVkZpMkcqXqYQi891pFL6w’ >>> jwt.decode(jwt_token, 'secret', algorithms=[ 'HS256']) {'payload': 'pycontw 2016'} 31 https://github.com/jpadilla/pyjwt pip install PyJWT see more in Registered Claim Names
  • 33. Copyright © 2016 ThroughTek Co., Ltd. All rights reserved. Confidential. Do not distribute. 33 • Generic applications • Customization service • Kalay Kit • FW integration micro-service system
  • 34. Kalay services Users Kalay AM Kalay DM JWT login Kalay DC mqtt/https shared keys shared keys shared keys Kalay Cloud Kalay services Kalay services devices actions (bind/view/control….) with JWT
  • 35. Messaging API for Mobile Apps and Websites ● http://api.diuit.com/
  • 36. Authentication with JWT for security purpose 1. User sends login request with credential 2. Auth user on your server (account server) 3. Request for Nonce on Diuit server 4. Obtain nonce from Diuit server 5. Use JWT to request session token 6. Obtain session token from Diuit server 7. Send session token back to messaging client 8. Authenticate messaging client on Diuit server using "loginWithAuthToken" JWT Your own account server user login nonce =>create JWT { "typ": "JWT", "alg": "RS256" "cty": "diuit-eit;v=1" "kid": ${EncryptionKeyId} } header { "iss": ${DIUIT_APP_ID} "sub": ${UNIQUE_USER_ID} "iat": ${CURRENT_TIME_IN_ISO8601_FORMAT} "exp":${SESSION_EXPIRATION_TIME_IN_ISO8601_FORMAT} "nce": ${AUTHENTICATION_NONCE} } payload
  • 37. Django REST framework JWT JSON Web Token Authentication support for Django REST Framework 37
  • 38. Django DRF JWT 38 https://github.com/GetBlimp/django-rest-framework-jwt Steps: ● pip install djangorestframework-jwt ● add JSONWebTokenAuthentication in Django REST framework's DEFAULT_AUTHENTICATION_CLASSES (settings.py) ● add URL routes (urls.py) ○ provide JWT token (obtain_jwt_token) ○ refresh token (refresh_jwt_token) ○ verify token (verify_jwt_token) ● additional settings Requirements ● Python (2.7, 3.3, 3.4) ● Django (1.8, 1.9) ● Django REST Framework (3.0, 3.1, 3.2, 3.3)
  • 39. settings.py 39 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } from rest_framework_jwt.views import obtain_jwt_token #... urlpatterns = patterns( '', # ... url(r'^api-token-auth/', obtain_jwt_token), url(r'^api-token-refresh/', refresh_jwt_token), url(r'^api-token-verify/', verify_jwt_token), ) urls.py http://getblimp.github.io/django-rest-framework-jwt/
  • 40. Flask-JWT Add basic JWT features to your Flask application 40 https://pythonhosted.org/Flask-JWT/
  • 41. Flask-JWT from flask import Flask from flask_jwt import JWT, jwt_required, current_identity from werkzeug.security import safe_str_cmp 41 https://pythonhosted.org/Flask-JWT/ pip install Flask-JWT class User(object): def __init__(self, id, username, password): self.id = id self.username = username self.password = password def __str__(self): return "User(id='%s')" % self.id users = [ User(1, 'user1', 'abcxyz'), User(2, 'user2', 'abcxyz'), ] username_table = {u.username: u for u in users} userid_table = {u.id: u for u in users} Minimum viable application configuration:
  • 42. 42 app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = ' super-secret' jwt = JWT(app, authenticate, identity ) def identity(payload): user_id = payload['identity'] return userid_table.get(user_id, None) def authenticate(username, password): user = username_table.get(username, None) if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')): return user @app.route('/protected') @jwt_required() def protected(): return '%s' % current_identity if __name__ == '__main__': app.run() Configuration JWT_AUTH_URL_RULE: The authentication endpoint URL. Defaults to /auth https://pythonhosted.org/Flask-JWT/ jwt working
  • 43. Recap ● JWT (‘jot’) : header, payload, signature ● Stateless token-based authentication ● Use libraries ● PyJWT, Django DRF JWT , Flask-JWT ● Provide, refresh, verify JWT 43
  • 44. About JWT Ref: ● JWT ● https://jwt.io/ ● https://auth0.com/learn/json-web-tokens/ ● https://self-issued.info/docs/draft-ietf-oauth-json-web-token.html ● PyJWT (https://pyjwt.readthedocs.org/) ● django-rest-framework-jwt (http://getblimp.github.io/django-rest-framework-jwt/) ● Flask-JWT (https://pythonhosted.org/Flask-JWT/) ● DjangoCon US 2014 talk on JWT https://speakerdeck.com/jpadilla/djangocon-json-web-tokens ● JWT in Auth0 https://auth0.com/blog/2014/12/02/using-json-web-tokens-as-api-keys/ About Authentication ● https://www.owasp.org/index.php/Authentication_Cheat_Sheet and others: ● Kalay platform (http://www.throughtek.com.tw/kalay_overview.html) ● diuit messaging api (http://api.diuit.com/ , https://github.com/diuitAPI) ● icons: (https://thenounproject.com/) 44