Skip to content

Instantly share code, notes, and snippets.

@jackiect
Forked from elnygren/django_jwt_cookie.py
Created October 28, 2020 16:03
Show Gist options
  • Save jackiect/38517ff2b81f054ecc945585105dffe4 to your computer and use it in GitHub Desktop.
Save jackiect/38517ff2b81f054ecc945585105dffe4 to your computer and use it in GitHub Desktop.

Revisions

  1. Elias Nygren revised this gist Oct 18, 2016. 1 changed file with 7 additions and 5 deletions.
    12 changes: 7 additions & 5 deletions django_jwt_cookie.py
    Original file line number Diff line number Diff line change
    @@ -44,7 +44,12 @@ def _get_session_key(self):
    generate a JWT Token with DRF-JWT.
    """
    session_cache = getattr(self, '_session_cache', {})
    return api_settings.JWT_ENCODE_HANDLER(session_cache)
    return api_settings.JWT_ENCODE_HANDLER({
    **session_cache,
    'exp': datetime.utcnow() + timedelta(seconds=settings.SESSION_COOKIE_AGE)
    # any other JWT fields like 'iss' etc. could be added here...
    # see: https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11
    })


    def jwt_session_middleware(get_response):
    @@ -62,10 +67,7 @@ def middleware(request):
    if field not in request.session:
    request.session[field] = getattr(request.user, field)

    request.session['exp'] = datetime.utcnow() + timedelta(seconds=settings.SESSION_COOKIE_AGE)

    # any other JWT fields like 'iss' etc. could be added here...
    # see: https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11
    # update 'exp' here if about the expire ?

    return response

  2. Elias Nygren revised this gist Oct 18, 2016. 1 changed file with 10 additions and 3 deletions.
    13 changes: 10 additions & 3 deletions django_jwt_cookie.py
    Original file line number Diff line number Diff line change
    @@ -10,16 +10,18 @@
    JWT_PAYLOAD_GET_USERNAME_HANDLER accordingly)
    """
    from datetime import datetime, timedelta

    from django.conf import settings
    from django.contrib.sessions.backends.signed_cookies import SessionStore as SignedCookieSessionStore
    from django.contrib.sessions.backends.signed_cookies import SessionStore

    from rest_framework_jwt.settings import api_settings


    JWT_USER_FIELDS = ['username',] # OR: load these from settings
    JWT_USER_FIELDS = ['email', 'slug'] # OR: load these from settings


    class SessionStore(SignedCookieSessionStore):
    class SessionStore(SessionStore):

    def load(self):
    """
    @@ -60,6 +62,11 @@ def middleware(request):
    if field not in request.session:
    request.session[field] = getattr(request.user, field)

    request.session['exp'] = datetime.utcnow() + timedelta(seconds=settings.SESSION_COOKIE_AGE)

    # any other JWT fields like 'iss' etc. could be added here...
    # see: https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/utils.py#L11

    return response

    return middleware
  3. Elias Nygren revised this gist Oct 17, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions django_jwt_cookie.py
    Original file line number Diff line number Diff line change
    @@ -11,15 +11,15 @@
    """
    from django.conf import settings
    from django.contrib.sessions.backends.signed_cookies import SessionStore
    from django.contrib.sessions.backends.signed_cookies import SessionStore as SignedCookieSessionStore

    from rest_framework_jwt.settings import api_settings


    JWT_USER_FIELDS = ['username',] # OR: load these from settings


    class SessionStore(SessionStore):
    class SessionStore(SignedCookieSessionStore):

    def load(self):
    """
  4. Elias Nygren revised this gist Oct 17, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion django_jwt_cookie.py
    Original file line number Diff line number Diff line change
    @@ -16,7 +16,7 @@
    from rest_framework_jwt.settings import api_settings


    JWT_USER_FIELDS = ['email', 'slug'] # OR: load these from settings
    JWT_USER_FIELDS = ['username',] # OR: load these from settings


    class SessionStore(SessionStore):
  5. Elias Nygren created this gist Oct 17, 2016.
    65 changes: 65 additions & 0 deletions django_jwt_cookie.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@
    """
    This file contains a custom Django SessionStore and middleware for using a JWT
    token inside the Django session cookie. The token plays well with Django Rest
    Framework and it's JWT library: django-rest-framework-jwt.
    Usage:
    - add this file to settings.py SESSION_ENGINE
    - add jwt_session_middleware to settings.py MIDDLEWARE
    - set JWT_USER_FIELDS (and configure django-rest-framework-jwt's
    JWT_PAYLOAD_GET_USERNAME_HANDLER accordingly)
    """
    from django.conf import settings
    from django.contrib.sessions.backends.signed_cookies import SessionStore

    from rest_framework_jwt.settings import api_settings


    JWT_USER_FIELDS = ['email', 'slug'] # OR: load these from settings


    class SessionStore(SessionStore):

    def load(self):
    """
    We load the data from the key itself instead of fetching from
    some external data store. Opposite of _get_session_key(),
    raises BadSignature if signature fails.
    """
    try:
    return api_settings.JWT_DECODE_HANDLER(self.session_key)
    except Exception:
    # BadSignature, ValueError, or unpickling exceptions. If any of
    # these happen, reset the session.
    self.create()
    return {}

    def _get_session_key(self):
    """
    Most session backends don't need to override this method, but we do,
    because instead of generating a random string, we want to actually
    generate a JWT Token with DRF-JWT.
    """
    session_cache = getattr(self, '_session_cache', {})
    return api_settings.JWT_ENCODE_HANDLER(session_cache)


    def jwt_session_middleware(get_response):
    """
    Middleware that adds JWT_USER_FIELDS into the session for all logged in Users.
    """

    def middleware(request):
    response = get_response(request)

    if request.user.is_anonymous:
    return response

    for field in JWT_USER_FIELDS:
    if field not in request.session:
    request.session[field] = getattr(request.user, field)

    return response

    return middleware