Git Product home page Git Product logo

django-jwt-auth's Introduction

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.

django-jwt-auth's People

Contributors

bskim45 avatar jpadilla avatar wesleylima avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-jwt-auth's Issues

CSRF verification failure

Hi,

Shouldn't jwt_auth.views.ObtainJSONWebToken be exempt from CSRF verification ? Mostly people go (or I at least ) for jwt solution to get rid of cookies authentication solution ?

If exempt CSRF is fine by the maintainer I'd be happy to submit a patch.

Plans?

I wanted to see what the plans are for the library? I've written the following add-ons:

  1. Middleware to auth any connection sending JWT in authorization header
  2. After login signal hook to create JWT and store it in session
  3. Template tag to output your JWT from your session

I wanted to see if any/all of those are of interest to you? If so, I'll make a PR(or multiple if you want them split up). If not, no big deal, I'll make a different library.

Rational here, we often have projects where just a part of the site/application is JS heavy and the rest is more of a traditional Django app. In that scenario, using the normal login and having a JWT that can be used from there is a great workflow.

str object not bytes

Haven't looked too far into this... but it looks like pyJWT is now returning a str from encode(..) rather than a bytes object. I suggest removing the .decode('utf-8') here

Release new version?

Thanks for the implementation!

I'm currently installing the package from a commit because I got some errors on 0.0.1 (with importlib being imported from Django). Could you release a new version to pypi?

Login_required decorator and authentication backend

Hi, I've just discovered this extension of djangorestframework-jwt .
I am wondering why the authentication is managed via JSONWebTokenAuthMixin and not using a custom authentication backend which would work fine with the @login_required decorator.

Thanks,
Sirion

Check that the user is the right one

I'm writing an API with Django and wanted to use JWT for handling authentication.

So I got everything working fine, however I could not quite understand how to check that the given user that is trying to do the API call is the that generated the token.

I found a way to do that just by having the user_id in the url like this:

class Save(JSONWebTokenAuthMixin, View):
    def post(self, request, applicant_id):
        applicant_id = int(applicant_id)
        content = request.POST.dict()
        # TODO: this obviously would run twice in this scenario
        # is there a way to do it only once??
        user, token = self.authenticate(request)
        if user.id != applicant_id:
            return HttpResponseForbidden("%d != %d" % (user.id, applicant_id))

        # TODO: do something with the request and return it back
        return HttpResponse(
            json.dumps(content),
            content_type='application/json',
            status=202,
        )

But calling the self.authenticate again does not seem very smart.
Isn't there another way to do that?

Maybe should self.authenticate set an attribute in the object with the user and the token?
Or there is a better way to do this altogether?

Thanks

doesn't work

I use only this lib and not installed django-rest-framework,and get the token with:

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

but when I use this token to curl other page,it return not logined in.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.