JWT Authentication with RSA with Django

  • JWT User Authentication using HS256
  • JWT User Authentication using RSA
  • JWT User Refresh Token
  • payload: contains the data representing the claims. It can contain reserved claims as in standard fields or user-defined ones (as we’re going to see later).
  • signature: used to validate the token. It is formed of the encoded header and payload signed using a custom secret.
signature = HMACSHA256( base64URLEncode(header)+”.”+base64URLEncode(payload), “secret”)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
{
"alg": "HS256",
"typ": "JWT"
}
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
JWT Authentication with HS256
pip install djangorestframework-jwt
INSTALLED_APPS = [
...
'rest_framework_jwt',
...
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_SECRET_KEY': 'This is a very long and secure secret key',
'JWT_GET_USER_SECRET_KEY': None,
'JWT_ALGORITHM': 'HS256',
'JWT_VERIFY': True,
'JWT_VERIFY_EXPIRATION': True,
'JWT_EXPIRATION_DELTA': datetime.timedelta(minutes=15),
'JWT_ISSUER': None,

'JWT_ALLOW_REFRESH': True,
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(minutes=20),
}
url(r'^token/obtain/$', Login.as_view(), name='authenticate-login'),
url(r'^token/refresh/', TokenRefresh.as_view()),
url(r'^token/verify/', verify_jwt_token),
authentication_classes = (JSONWebTokenAuthentication,)
permission_classes = (IsAuthenticated,)
JWT Authentication Workflow with RSA
JWT Authentication for multiple susbsytems
JWT_AUTH = {    'JWT_PUBLIC_KEY': open(JWT_PUBLIC_KEY_PATH).read(),
'JWT_PRIVATE_KEY': open(JWT_PRIVATE_KEY_PATH).read(),
'JWT_ALGORITHM': 'RS256',
...
}
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
urlpatterns = [     ...
url(r'^api-token-refresh/', refresh_jwt_token),
]

former @Salesforce > ETL-ing my experience and learnings into short stories

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store