Package: webstack-django-jwt-auth
Django JWT AuthOverviewThis package providesJSON Web Token
Authenticationsupport for Django by usingPyJWT.The project is a fork of (https://github.com/jpadilla/django-jwt-auth) created
by José Padilla (maintainer of PyJWT too). José doesn't seem to have the time
anymore to work on django-jwt-auth.New features from original code:refresh tokenprovides 2 middlewaresDjango 3.0+better coverage and packagingInstallationInstall usingpip...pipinstallwebstack-django-jwt-authUsageIn yoururls.pyadd the following URL route to enable obtaining a token via a
POST included the user's username and password.fromjwt_authimportviewsasjwt_auth_viewsfromyour_app.viewsimportRestrictedViewurlpatterns=[# ...path("token-auth/",jwt_auth_views.jwt_token),path("token-refresh/",jwt_auth_views.refresh_jwt_token),path("protected-url/",RestrictedView.as_view()),]Inside your_app, create a Django restricted view:importjsonfromdjango.httpimportJsonResponsefromdjango.views.genericimportViewfromjwt_auth.mixinsimportJSONWebTokenAuthMixinclassRestrictedView(JSONWebTokenAuthMixin,View):defget(self,request):data={"foo":"bar","username":request.user.username,}returnJsonResponse(data)You can easily test if the endpoint is working by doing the following in your
terminal, if you had a user created with the usernameadminand passwordabc123.curl-XPOST-H"Content-Type: application/json"-d'{"username":"admin","password":"abc123"}'http://localhost:8000/token-auth/Now in order to access protected api urls you must include theAuthorization: Bearer <your_token>header.curl-H"Authorization: Bearer <your_token>"http://localhost:8000/protected-url/There is also a provided middleware if you would prefer that to the view
integration. Just add the following to your middleware:MIDDLEWARE=(# ...'jwt_auth.middleware.JWTAuthenticationMiddleware',)Additional SettingsThere are some additional settings that you can override similar to how you'd do
it with Django REST framework itself. Here are all the available defaults.JWT_ALGORITHM='HS256'JWT_ALLOW_REFRESH=FalseJWT_AUDIENCE=NoneJWT_AUTH_HEADER_PREFIX='Bearer'JWT_DECODE_HANDLER='jwt_auth.utils.jwt_decode_handler',JWT_ENCODE_HANDLER='jwt_auth.utils.jwt_encode_handler'JWT_EXPIRATION_DELTA=datetime.timedelta(seconds=300)JWT_LEEWAY=0JWT_LOGIN_URLS=[settings.LOGIN_URL]JWT_PAYLOAD_GET_USER_ID_HANDLER='jwt_auth.utils.jwt_get_user_id_from_payload_handler'JWT_PAYLOAD_HANDLER='jwt_auth.utils.jwt_payload_handler'JWT_REFRESH_EXPIRATION_DELTA=datetime.timedelta(days=7)JWT_SECRET_KEY:SECRET_KEYJWT_VERIFY=TrueJWT_VERIFY_EXPIRATION=TrueThis packages uses the JSON Web Token Python implementation,PyJWTand allows to modify some of it's
available options.JWT_ALGORITHMPossible values:HS256 - HMAC using SHA-256 hash algorithm (default)HS384 - HMAC using SHA-384 hash algorithmHS512 - HMAC using SHA-512 hash algorithmRS256 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-256 hash algorithmRS384 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-384 hash algorithmRS512 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-512 hash algorithmNote:For the RSASSA-PKCS1-v1_5 algorithms, the "secret" argument in jwt.encode is
supposed to be a private RSA key as imported with
Crypto.PublicKey.RSA.importKey. Likewise, the "secret" argument in jwt.decode
is supposed to be the public RSA key imported with the same method.Default is"HS256".JWT_ALLOW_REFRESHEnable token refresh functionality. Token issued fromjwt_auth.views.jwt_tokenwill have anorig_iatfield.Default isFalseJWT_AUDIENCETypically, the base address of the resource being accessed, eghttps://example.com.JWT_AUTH_HEADER_PREFIXYou can modify the Authorization header value prefix that is required to be sent
together with the token.Default isBearer.JWT_EXPIRATION_DELTAThis is an instance of Python'sdatetime.timedelta. This will be added todatetime.utcnow()to set the expiration time.Default isdatetime.timedelta(seconds=300)(5 minutes).JWT_LEEWAYThis allows you to validate an expiration time which is in the past but no
very far. For example, if you have a JWT payload with an expiration time set
to 30 seconds after creation but you know that sometimes you will process it
after 30 seconds, you can set a leeway of 10 seconds in order to have some
margin.Default is0seconds.JWT_LOGIN_URLSSet the list of URLs that will be used to authenticate the user, you should take
care to set only required URLs because the middleware will accept
non-authenticated requests (no JWT) to these endpoints.JWT_PAYLOAD_GET_USER_ID_HANDLERIf you storeuser_iddifferently than the default payload handler does,
implement this function to fetchuser_idfrom the payload.JWT_PAYLOAD_HANDLERSpecify a custom function to generate the token payloadJWT_REFRESH_EXPIRATION_DELTALimit on token refresh, is adatetime.timedeltainstance. This is how much
time after the original token that future tokens can be refreshed from.Default isdatetime.timedelta(days=7)(7 days).JWT_SECRET_KEYThis is the secret key used to encrypt the JWT. Make sure this is safe and not
shared or public.Default is your project'ssettings.SECRET_KEY.JWT_VERIFYIf the secret is wrong, it will raise a jwt.DecodeError telling you as such. You
can still get at the payload by setting theJWT_VERIFYtoFalse.Default isTrue.JWT_VERIFY_EXPIRATIONYou can turn off expiration time verification with by settingJWT_VERIFY_EXPIRATIONtoFalse.Default isTrue.