• Stars
    star
    164
  • Rank 230,032 (Top 5 %)
  • Language
    Python
  • License
    MIT License
  • Created about 10 years ago
  • Updated about 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JSON Web Token Authentication support for Django

Django JWT Auth

build-status-image pypi-version

Overview

This package provides JSON Web Token Authentication support for Django.

Based on the Django REST Framework JWT Auth package.

Installation

Install using pip...

$ pip install django-jwt-auth

Usage

In your urls.py add the following URL route to enable obtaining a token via a POST included the user's username and password.

from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token

urlpatterns = [
    # ...

    url(r'api-token-auth/', obtain_jwt_token),
    url(r'api-token-refresh/', refresh_jwt_token),
]

You can easily test if the endpoint is working by doing the following in your terminal, if you had a user created with the username admin and password abc123.

$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"abc123"}' http://localhost:8000/api-token-auth/

Now in order to access protected api urls you must include the Authorization: Bearer <your_token> header.

$ curl -H "Authorization: Bearer <your_token>" http://localhost:8000/protected-url/

Additional Settings

There 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_ENCODE_HANDLER = 'jwt_auth.utils.jwt_encode_handler'
JWT_DECODE_HANDLER = 'jwt_auth.utils.jwt_decode_handler',
JWT_PAYLOAD_HANDLER = 'jwt_auth.utils.jwt_payload_handler'
JWT_PAYLOAD_GET_USER_ID_HANDLER = 'jwt_auth.utils.jwt_get_user_id_from_payload_handler'
JWT_SECRET_KEY: SECRET_KEY
JWT_ALGORITHM = 'HS256'
JWT_VERIFY = True
JWT_VERIFY_EXPIRATION = True
JWT_LEEWAY = 0
JWT_EXPIRATION_DELTA = datetime.timedelta(seconds=300)
JWT_ALLOW_REFRESH = False
JWT_REFRESH_EXPIRATION_DELTA = datetime.timedelta(days=7)
JWT_AUTH_HEADER_PREFIX = 'Bearer'

This packages uses the JSON Web Token Python implementation, PyJWT and allows to modify some of it's available options.

JWT_SECRET_KEY

This is the secret key used to encrypt the JWT. Make sure this is safe and not shared or public.

Default is your project's settings.SECRET_KEY.

JWT_ALGORITHM

Possible values:

  • HS256 - HMAC using SHA-256 hash algorithm (default)
  • HS384 - HMAC using SHA-384 hash algorithm
  • HS512 - HMAC using SHA-512 hash algorithm
  • RS256 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-256 hash algorithm
  • RS384 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-384 hash algorithm
  • RS512 - RSASSA-PKCS1-v1_5 signature algorithm using SHA-512 hash algorithm

Note:

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_VERIFY

If the secret is wrong, it will raise a jwt.DecodeError telling you as such. You can still get at the payload by setting the JWT_VERIFY to False.

Default is True.

JWT_VERIFY_EXPIRATION

You can turn off expiration time verification with by setting JWT_VERIFY_EXPIRATION to False.

Default is True.

JWT_LEEWAY

This 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 is 0 seconds.

JWT_EXPIRATION_DELTA

This is an instance of Python's datetime.timedelta. This will be added to datetime.utcnow() to set the expiration time.

Default is datetime.timedelta(seconds=300)(5 minutes).

JWT_ALLOW_REFRESH

Enable token refresh functionality. Token issued from rest_framework_jwt.views.obtain_jwt_token will have an orig_iat field. Default is False

JWT_REFRESH_EXPIRATION_DELTA

Limit on token refresh, is a datetime.timedelta instance. This is how much time after the original token that future tokens can be refreshed from.

Default is datetime.timedelta(days=7) (7 days).

JWT_PAYLOAD_HANDLER

Specify a custom function to generate the token payload

JWT_PAYLOAD_GET_USER_ID_HANDLER

If you store user_id differently than the default payload handler does, implement this function to fetch user_id from the payload.

JWT_AUTH_HEADER_PREFIX

You can modify the Authorization header value prefix that is required to be sent together with the token.

Default is Bearer.

More Repositories

1

pyjwt

JSON Web Token implementation in Python
Python
4,883
star
2

django-rest-framework-jwt

JSON Web Token Authentication support for Django REST Framework
Python
3,185
star
3

django-project-template

Project template layout for Django 3.0+
Python
691
star
4

django-dotenv

Loads environment variables from .env
Python
570
star
5

juicebox

A virtual machine designed for programming workshops.
Shell
533
star
6

redisapp

The easiest way to get started with Redis on the Mac
Objective-C
351
star
7

black-playground

psf/black online demo
JavaScript
160
star
8

cookiecutter-django-rest-framework

A cookiecutter template for creating reusable Django REST Framework packages quickly.
Python
90
star
9

django-rest-framework-xml

XML support for Django REST Framework
Python
86
star
10

rabbitmqapp

The easiest way to get started with RabbitMQ on the Mac
Objective-C
66
star
11

django-rest-framework-oauth

OAuth support for Django REST Framework
Python
59
star
12

ember-fastboot-docker

Dockerized Node.js server for running Ember FastBoot apps
JavaScript
42
star
13

postmark-inbound-python

Python Wrapper for Postmark Inbound
Python
37
star
14

feedleap

Your RSS feeds as Clips in a Kippt List
CSS
36
star
15

django-rest-framework-yaml

YAML support for Django REST Framework
Python
31
star
16

ember-poe

Simple Markdown editor Ember Application using localStorage
CoffeeScript
29
star
17

tumblr-to-ghost

Tumblr exporter to Ghost importer
Python
26
star
18

telegram-gate

Las 889 páginas de Telegram entre Rosselló Nevares y sus allegados
JavaScript
26
star
19

tracking-luma-outages

Record de datos de interrupciones de servicio reportados por LUMA Energy en Puerto Rico a través de el portal de Mi LUMA.
Python
25
star
20

yapf-online

google/yapf online demo
HTML
24
star
21

django-rest-framework-jsonp

JSONP support for Django REST Framework
Python
21
star
22

mandrill-inbound-python

Python Wrapper for Mandrill Inbound Email
Python
20
star
23

notaso

Conoce a tus profesores antes de llegar al salón.
JavaScript
19
star
24

dotfiles

This is a collection of my dotfiles for Mac OS X.
Shell
18
star
25

statsd-graphite-vm

Vagrant VM for StatsD + Graphite
Ruby
16
star
26

ivona-go

Go client library for IVONA Speech Cloud API
Go
15
star
27

heroku-flower

Deploy Flower to Heroku
14
star
28

tracking-status-pr

This tool scrapes status.pr every hour and keeps tracks of changing metrics in order to help visualize and measure progress.
Python
14
star
29

HackerDesignerNews

Hacker News and Designer News Aggregator and Web API
JavaScript
13
star
30

codeigniter-s3-swfupload

Uploading directly to S3 using Codeigniter and swfUpload
13
star
31

designer-news-python

Python library for the Designer News API
Python
11
star
32

barcampinator

Barcamp user registration tool + presentation display
JavaScript
10
star
33

ember-clipboard

Ember.js addon component for clipboard.js
JavaScript
8
star
34

thenews-api

Scraper and Web API for thenews.im
JavaScript
7
star
35

WallIt

A fun geolocation app powered by ACS. Inspired by Anywall(which is powered by Parse)
JavaScript
6
star
36

tracking-gov-pr

Tracking gov.pr properties
Python
6
star
37

alchemyapi-go

Go client library for AlchemyAPI
Go
6
star
38

apex-chat

Las 72 páginas del chat de APEX entre Robert Rodriguez y sus allegados
JavaScript
3
star
39

datasette-mortalidad

Herramienta para explorar la Base de Datos de Mortalidad en Puerto Rico
Python
3
star
40

better-endi

Browser extensions to bypass transition ads in endi.com
JavaScript
2
star
41

npm-repo

Redirect to an npm package's repository
JavaScript
2
star
42

bokamerki

CSS
1
star
43

oghowto

1
star
44

vagrant-example

Playing around with Vagrant and Chef
Ruby
1
star
45

email-hangman

Hangman via email
Python
1
star
46

rttm

Go
1
star
47

py-backwards-online

py-backwards online demo
HTML
1
star
48

auth0-quiz

A Quiz generator for questions regarding security, authorization and authentication. You can use this to create any quiz you want.
JavaScript
1
star
49

glimmer-electron-demo

Run glimmer in electron with the help of ember-electron
JavaScript
1
star
50

remindeat

Never forget what you've already ate at a restaurant
Python
1
star
51

ember-hn-clone

A Hacker News / Designer News clone built with Ember.js
JavaScript
1
star