A JSON Web Token authentication plugin for the Django REST Framework.

Overview
Issues
  • Looking for maintainers (and Thank You to the community!)

    Looking for maintainers (and Thank You to the community!)

    Hey folks! So Simple JWT has really come a ways in terms of popularity (further than I probably would have imagined). For that, I owe a big "Thank you!" to the community of Django and REST devs that have used and contributed to the project!

    However, for a while now I haven't had a lot of time to devote to addressing issues and feature requests. My professional life dominates my schedule and it also hasn't tended to involve much REST API development in recent years. But the library continues to enjoy widespread use. Contributors request/develop features and identify usability/security issues on a daily basis. I don't have enough time in my personal schedule to serve all of the community's needs! But I want to see the project continue to succeed.

    For that reason, I'm interested in hearing from any devs that wish to become involved in maintaining this project. I'm particularly interested in hearing from devs who have contributed to this project in the past and/or who can demonstrate experience with similar engineering projects. Significant histories of open source contribution are obviously a plus! If you're located in Boulder, CO (which is in the US), that's also a huge plus. We could potentially meet in person to get acquainted.

    Please reply to this issue if you think you match the above criteria! I'm looking forward to hearing from all of you!

    opened by davesque 55
  • Add integration instructions for drf-yasg

    Add integration instructions for drf-yasg

    Fixes https://github.com/axnsan12/drf-yasg/issues/407

    docs 
    opened by johnthagen 31
  • Implement Jazzband guidelines for django-rest-framework-simplejwt

    Implement Jazzband guidelines for django-rest-framework-simplejwt

    This issue tracks the implementation of the Jazzband guidelines for the project django-rest-framework-simplejwt

    It was initiated by @davesque who was automatically assigned in addition to the Jazzband roadies.

    See the TODO list below for the generally required tasks, but feel free to update it in case the project requires it.

    Feel free to ping a Jazzband roadie if you have any question.

    TODOs

    • [x] Fix all links in the docs (and README file etc) from old to new repo
    • [x] Add the Jazzband badge to the README file
    • [x] Add the Jazzband contributing guideline to the CONTRIBUTING.md or CONTRIBUTING.rst file
    • [x] Port continuous testing to GitHub Actions (away from Circle, see previous migrations in https://github.com/orgs/jazzband/projects/1)
    • [x] Check if test coverage services work (must be Codecov, etc)
    • [x] Add jazzband account to PyPI project as maintainer role (e.g. URL: https://pypi.org/manage/project/django-rest-framework-simplejwt/collaboration/)
    • [x] Add jazzband-bot as maintainer to the Read the Docs project (e.g. URL: https://readthedocs.org/dashboard/django-rest-framework-simplejwt/users/)
    • [x] Add incoming GitHub webhook integration to Read the Docs project (e.g. URL: https://readthedocs.org/dashboard/django-rest-framework-simplejwt/integrations/)
    • [x] Fix project URL in GitHub project description
    • [x] Review project if other services are used and port them to Jazzband
    • [x] Decide who is project lead for the project (if at all) (@davesque and @Andrew-Chen-Wang)
    • [x] Set up CI for Jazzband project releases if needed and open ticket if yes

    Project details

    Description A JSON Web Token authentication plugin for the Django REST Framework.
    Homepage https://django-rest-framework-simplejwt.readthedocs.io/
    Stargazers 2236
    Open issues 81
    Forks 351
    Default branch master
    Is a fork False
    Has Wiki True
    Has Pages False
    enhancement help wanted 
    opened by jazzband-bot 26
  • Example SimpleJWT repositories: Contribute!

    Example SimpleJWT repositories: Contribute!

    Hi all! Due to the sheer number of requests and urges for #157 to be merged, I have created a template repository with a Django server ready-to-go. To generate a sample repository for SimpleJWT, please press the "Use this template" button so that you don't fork the repository; this way, you can rename the repository to whatever name you want (although please follow naming conventions of the React and Vue.js repos already setup. It'd be great if you could also transfer ownership to the SimpleJWT organization so that everyone knows about it -- i.e. viewable -- and can be maintained by the community).

    The template repository: https://github.com/SimpleJWT/drf-SimpleJWT-server-template

    Currently created repositories:

    • [X] iOS and Android (complete): https://github.com/Andrew-Chen-Wang/mobile-auth-example
    • [ ] Angular (in progress): https://github.com/SimpleJWT/drf-SimpleJWT-Angular
    • [X] React (Complete): https://github.com/SimpleJWT/drf-SimpleJWT-React
    • [X] VueJS (Complete): https://github.com/SimpleJWT/drf-SimpleJWT-Vue

    In the future:

    • React Native
    • Flutter browser
    • Flutter mobile

    There are other frontend frameworks like Angular (JS), Flutter (Dart), Ember (JS), etc. If I didn't create them, it just means I undervalue them (jk). I just don't want to get ahead of myself. If you want to contribute and you're using one of these frameworks, by all means @Andrew-Chen-Wang (i.e. mention me) in this issue, and I will create a repository for you.

    To reiterate, you will need unittest cases. For those who want the #157 merger, at least two frontend frameworks that are used on web browsers must be completed and tested to have the PR to be considered for merger. Not only that, it must use the PR's latest commit (do not use master branch; specify a commit SHA). I cannot stress this enough: security is number one priority. To publish a package with, imo, still a highly insecure PR since there is still no one who has given me a single test repository, SimpleJWT would be doomed in vulnerabilities and CVEs.

    So.... Thanks for contributing Djangonauts!

    enhancement help wanted 
    opened by Andrew-Chen-Wang 22
  • AttributeError: 'str' object has no attribute 'decode'.

    AttributeError: 'str' object has no attribute 'decode'.

    Hey– I'm trying to get this package integrated and I'm getting something odd here when a jwt is being created. Is anyone else running into this issue? I'm on 4.4.0

    AttributeError: 'str' object has no attribute 'decode'.

      File "/.../.venv/lib/python3.7/site-packages/rest_framework_simplejwt/tokens.py", line 226, in for_user
        token=str(token),
      File "/.../.venv/lib/python3.7/site-packages/rest_framework_simplejwt/tokens.py", line 82, in __str__
        return token_backend.encode(self.payload)
      File "/.../.venv/lib/python3.7/site-packages/rest_framework_simplejwt/backends.py", line 43, in encode
        return token.decode('utf-8')
    AttributeError: 'str' object has no attribute 'decode'
    
    bug 
    opened by aaronn 20
  • how to change the database table used by simplejwt to authenticate user for generating token instead of using auth_user table?

    how to change the database table used by simplejwt to authenticate user for generating token instead of using auth_user table?

    I couldn't find the configuration to use some specific table to generate the token instead of auth_user table

    question 
    opened by yash0307jain 19
  • Release new version to PyPI

    Release new version to PyPI

    Could a new release be pushed to PyPI that includes #186?

    For users using Django 3.0, django-rest-framework-simplejwt currently throws a warning. If running unit tests with -Werror, this causes builds to failed unless the warning is suppressed.

    enhancement 
    opened by johnthagen 18
  • Possible bug: 'str' object has no attribute 'decode' after PyJWT upgrade from 2.0.0a1 to 2.0.0

    Possible bug: 'str' object has no attribute 'decode' after PyJWT upgrade from 2.0.0a1 to 2.0.0

    Recently the PyJWT package has been updated and is throwing this error when generating a token.

    PyJWT latest version: https://github.com/jpadilla/pyjwt/releases/tag/2.0.0

    The exception is raised in: rest_framework_simplejwt/backends.py in encode at line 43

    just in return token.decode('utf-8') line

    I have solved it by explicitly putting the PyJWT package in my requirements.txt file, just below djangorestframework-simplejwt

    version that introduces the error: PyJWT==2.0.0

    downgraded version to make it work: PyJWT==v1.7.1

    duplicate 
    opened by salazarfelipe 17
  • Usage of authenticate function in TokenObtainSerializer

    Usage of authenticate function in TokenObtainSerializer

    class TokenObtainSerializer(serializers.Serializer):
        username_field = User.USERNAME_FIELD
    
        def __init__(self, *args, **kwargs):
            super(TokenObtainSerializer, self).__init__(*args, **kwargs)
    
            self.fields[self.username_field] = serializers.CharField()
            self.fields['password'] = PasswordField()
    
        def validate(self, attrs):
            self.user = authenticate(**{
                self.username_field: attrs[self.username_field],
                'password': attrs['password'],
            })
            if self.user is None or not self.user.is_active:
                raise serializers.ValidationError(
                    _('No active account found with the given credentials'),
                )
    
            return {}
    

    TokenObtainSerializer is using authenticate function which makes it impossible use something else than User.USERNAME_FIELD for authentication.

    Let's say I set username_field to something else than User.USERNAME_FIELD, for example email (and assume User.USERNAME_FIELD equals to username). Is this going to work? authenticate function is going to use User.USERNAME_FIELD = username but serializer has received email field.

    opened by JerzySpendel 16
  • Blacklist access token

    Blacklist access token

    How to blacklist access token along with refresh token, only able to blacklist refresh token?

    opened by theayash 15
  • BlackListedToken has no attribute 'objects'

    BlackListedToken has no attribute 'objects'

    Hello! Awesome library, keep up the good work!

    I encountered a bug in the latest release which boils down to the following lines https://github.com/jazzband/djangorestframework-simplejwt/blob/4d7c7649813f9eae4bd28ed17da685cd3a61f2fe/rest_framework_simplejwt/serializers.py#L141-L151

      File "/home/user/.cache/pypoetry/virtualenvs/MSWA2ZbW-py3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 436, in run_validation
        value = self.validate(value)
      File "/home/user/.cache/pypoetry/virtualenvs/MSWA2ZbW-py3.8/lib/python3.8/site-packages/rest_framework_simplejwt/serializers.py", line 150, in validate
        if BlacklistedToken.objects.filter(token__jti=jti).exists():
    AttributeError: type object 'BlacklistedToken' has no attribute 'objects'
    

    I think whats happening here is that since I don't have the blacklisted app in my installed apps as I dont require it, the BlacklistedToken model is being set as abstract=True and since we aren't specifically checking the presence of the app in the above lines, this error happened

    bug 
    opened by Kandeel4411 15
  • Has anyone implemented this experimental feature JWTTokenUserAuthentication backend?

    Has anyone implemented this experimental feature JWTTokenUserAuthentication backend?

    So I've been trying to build a Django project that handles authentication centrally on a standalone basis using django-rest-framework-simplejwt. And other Django Rest Framework projects that use this for authentication. All projects will have their own databases.

    I am not quite sure what goes into the database section in settings.py of both the auth project and other projects. The documentation mentions something about JWTTokenUserAuthentication backend as an experimental feature and is quite inadequate.

    I have done some research and found I may have to use a remote user login or set up a proxy server. Can someone point me in the right direction?

    question 
    opened by Abishek05 14
  • Why is there a database hit at every request ?

    Why is there a database hit at every request ?

    Hi and thanks in advance,

    I've successfully setup JWT authentication using django-rest-framework-simplejwt and React but I'm still very confused about the advantages and specifically database hits. I'm using simplejwt with ROTATE_REFRESH_TOKENS': True 'BLACKLIST_AFTER_ROTATION': True, when my access_token expire I ask for a new one through /api/token/refresh and it blacklist old tokens, I'm using axios interceptors to perform that automatically.

    But in my understanding the benefits of JWt is that they are stateless, meaning I don't have to hit the user database table everytime I want to make an a request that needs authentication permission. The problem is even with a simple view like this :

    class IsConnecteddAPI(APIView):
    
        permission_classes = [permissions.IsAuthenticated]
    
        def get(self, request, *args, **kwargs):
            data = "You seem to be connected"
    
            return Response(data, status=status.HTTP_200_OK)
    

    using django-silk I see that it still performs 1 query to my user table when my access token is valid , is that normal ? I'm really confused.

    Here are django silk outputs screen1 screen2 screen3 screen4

    Isn't get_user from https://github.com/SimpleJWT/django-rest-framework-simplejwt/blob/master/rest_framework_simplejwt/authentication.py hiting the user object everytime ?

    I've already asked the question on reddit and SO and they advised me to remove AuthMiddleware, so I removed both 'django.middleware.csrf.CsrfViewMiddleware' and 'django.contrib.auth.middleware.AuthenticationMiddleware' but I still get the same result. Setting permissions_classes to AllowAny doesn't vhange anything either.

    That's my axios code if needed :

    import axios from "axios";
    
    
    const baseURL = "http://localhost:5000";
    
    const axiosInstance = axios.create({
      baseURL: baseURL,
      timeout: 5000,
      headers: {
        Authorization: localStorage.getItem("accesstoken")
          ? "JWT " + localStorage.getItem("accesstoken")
          : null,
        "Content-Type": "application/json",
        accept: "application/json",
      },
    });
    
    const axioAnonymousInstance = axios.create({
      baseURL: baseURL,
      timeout: 5000,
      headers: {
        "Content-Type": "application/json",
        accept: "application/json",
      },
    });
    
    axiosInstance.interceptors.response.use(
      (response) => {
        return response;
      },
      async function (error) {
        const originalRequest = error.config;
    
        if (typeof error.response === "undefined") {
          alert(
            "A server/network error occurred. " +
              "Looks like CORS might be the problem. " +
              "Sorry about this - we will get it fixed shortly."
          );
          return Promise.reject(error);
        }
    
        if (
          error.response.status === 401 &&
          originalRequest.url === baseURL + "token/refresh/"
        ) {
          window.location.href = "/login/";
          return Promise.reject(error);
        }
    
        if (
          error.response.data.code === "token_not_valid" &&
          error.response.status === 401 &&
          error.response.statusText === "Unauthorized"
        ) {
          const refreshToken = localStorage.getItem("refreshtoken");
    
          if (refreshToken) {
            const tokenParts = JSON.parse(atob(refreshToken.split(".")[1]));
    
            // exp date in token is expressed in seconds, while now() returns milliseconds:
            const now = Math.ceil(Date.now() / 1000);
            console.log(tokenParts.exp);
    
            if (tokenParts.exp > now) {
              return axioAnonymousInstance
                .post("/api/token/refresh/", { refresh: refreshToken })
                .then((response) => {
                  localStorage.setItem("accesstoken", response.data.access);
                  localStorage.setItem("refreshtoken", response.data.refresh);
    
                  axiosInstance.defaults.headers["Authorization"] =
                    "JWT " + response.data.access;
                  originalRequest.headers["Authorization"] =
                    "JWT " + response.data.access;
    
                  return axiosInstance(originalRequest);
                })
                .catch((err) => {
                  // redirect ro /login here if wanted
                  console.log("axios Safe Instance error");
                  console.log(err);
                  // window.location.href = "/login/";
                });
            } else {
              console.log("Refresh token is expired", tokenParts.exp, now);
              window.location.href = "/login/";
            }
          } else {
            console.log("Refresh token not available.");
            window.location.href = "/login/";
          }
        }
    
        // specific error handling done elsewhere
        return Promise.reject(error);
      }
    );
    
    export { axiosInstance, axioAnonymousInstance };
    
    

    ( I know I shouldn't use localStorage but whatever )

    and I would typically just call this function to make the simple request to the view written above :

     const IsConnected = () => {
        axiosInstance
          .get("/api/is_connected/")
          .then((response) => {
            if (response.status === 200) {
              console.log(response.data);
              console.log("Is connected : CONNECTED ");
            } else {
              console.log("IS connected : not connected");
            }
          })
          .catch((error) => {
            console.log("Is connected : NOT CONNECTED");
            console.log(error);
          });
      };
    
    
    question 
    opened by StitiFatah 14
  • Why I can't delete OutstandingToken via django-admin

    Why I can't delete OutstandingToken via django-admin

    I'm using Blacklist app and if I try to delete one of my users I get the error message

    Deleting the selected user would result in deleting related objects, but your account doesn't have permission to delete the folowing types of objects: - outstanding token
    

    The OutstandingTokenAdmin's has_delete_permission method always returns False. So even admin user with superuser status can't delete this.

    Is there a reason to forbid deletion of OutstandingTokens?

    It's strange but I'm new to all this jwt stuff and maybe I miss something.

    opened by wwarne 13
  • Using a custom User model with SimpleJWT

    Using a custom User model with SimpleJWT

    Hi, I'm trying to use a custom User model/extension of the default Django auth.User model in my application.

    I created the User and Manager like so:

    import uuid
    
    from django.contrib.auth.base_user import BaseUserManager
    from django.contrib.auth.models import AbstractUser
    from django.db import models
    
    
    class CustomUserManager(BaseUserManager):
        def create_user(self, email, company_name, password=None):
            if not email:
                raise ValueError("User must have an email address.")
            if not company_name:
                raise ValueError("User must have a company name.")
    
            user = self.model(email=self.normalize_email(email),
                              company_name=company_name,
                              )
    
            user.set_password(password)
            user.save(using=self._db)
            return user
    
        def create_superuser(self, email, company_name, password):
            user = self.create_user(email=self.normalize_email(email),
                                    company_name=company_name,
                                    password=password,
                                    )
    
            user.is_admin = True
            user.is_staff = True
            user.is_superuser = True
            user.save(using=self._db)
            return user
    
    
    class CustomUser(AbstractUser):
        id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
        username = None
        email = models.EmailField(verbose_name="email", max_length=60, unique=True)
        company_name = models.CharField(max_length=30)
    
        # The following fields are required for every custom User model
        last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
        date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
        is_admin = models.BooleanField(default=False)
        is_active = models.BooleanField(default=True)
        is_staff = models.BooleanField(default=False)
        is_superuser = models.BooleanField(default=False)
    
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = ['company_name']
    
        objects = CustomUserManager()
    
        def __str__(self):
            return self.email
    
        def has_perm(self, perm, obj=None):
            return self.is_superuser
    
        def has_module_perms(self, app_label):
            return True
    

    but when I create users of this model and try to login into my app with them instead of getting a JWT token like before I get a message stating that there are no active users with those credentials...

    How can I use SimpleJWT with a custom User model?

    Thanks

    question 
    opened by obvionaoe 12
  • Customize which user can login

    Customize which user can login

    For one of my projects, I want a user first to confirm their email before they can log in. For this, I use the package django-simple-email-confirmation which extends the user with a boolean is_confirmed. To achieve this behavior I have to either do some syncing with the build-in user.is_active or I have to overwrite TokenObtainSerializer.validate().

    So what I would like to propose is a setting SIMPLE_JWT['user_login_rule'] = 'path.to.some.file.function' which returns a boolean and is called here in the TokenObtainSerializer.

    This would also resolve the issue #137

    If desired I could create a PR.

    enhancement help wanted 
    opened by t-io 12
  • How should I create or authenticate a JWT per view?

    How should I create or authenticate a JWT per view?

    Hello,

    Is there a way to generate or authenticate a token to grant access only for a specified view and be invalid on other views?

    This may sound odd but I want to issue a JWT token to share some info with frontend and grant access to a sensitive view, I'm using JWT at another view too but it is less important than this one.

    When I started to think about both, I found that if someone swapped one with another it will pass through verification and authentication as it's a valid JWT token issued by me but not for a specific view, so is there a way to do that?

    Should I make my custom JWT authentication class, verify class and check for my required payload too? or there is something more simple? or should I use something else, but JWT is the one here because you need to share some info with the client.

    Should I change secret and issue the new one with a different secret? should I use PyJWT? I don't care about linking it to a user, I'm even using AnonymousUser for the existing one, what do you think?

    Thanks, everyone

    invalid question 
    opened by mohmyo 12
  • 'str' object has no attribute 'decode'

    'str' object has no attribute 'decode'

    image

    This my code on urls.py

    from django.contrib import admin
    from django.urls import path
    from rest_framework_simplejwt import views as jwt_views
    from core.views import HelloView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
        path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
        path('hello/', HelloView.as_view(), name='hello'),
    ]
    

    settings.py

    ...
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
    ]
    ...
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ],
    }
    ...
    

    views.py

    from django.shortcuts import render
    
    # Create your views here.
    from rest_framework.views import APIView
    from rest_framework.response import Response
    from rest_framework.permissions import IsAuthenticated
    
    
    class HelloView(APIView):
        permission_classes = (IsAuthenticated,)
    
        def get(self, request):
            content = {'message': 'Hello, World!'}
            return Response(content)
    
    duplicate 
    opened by dimasanwaraziz 11
  • Makemigrations create new migrations for models in token_blacklist app

    Makemigrations create new migrations for models in token_blacklist app

    Hello,

    Everytime I try to run the migrations for my apps in django, new migrations are created for the token_blacklist applications. Is this how it's supposed to be? Currently found on versions 4.5.0 and 4.6.0.

    Your models in app(s): 'token_blacklist' have changes that are not yet reflected in a migration, and so won't be applied.
      Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
    [email protected]:/app# python manage.py makemigrations
    Migrations for 'token_blacklist':
      /usr/local/lib/python3.9/site-packages/rest_framework_simplejwt/token_blacklist/migrations/0008_auto_20210424_0948.py
        - Alter field id on blacklistedtoken
        - Alter field id on outstandingtoken
    
    bug 
    opened by Alig1493 11
  • Add jwks support

    Add jwks support

    In some cases for RSA the tokens are rotated and we need a way of resolving the tokens from a JWK_URL.

    Since pyjwt ===2.0.0 they added a pyjwkclient that has inbuilt caching of the keys: https://github.com/jpadilla/pyjwt/blob/79c23d7d9d32364be8f94680d8eda7135c3a15d5/jwt/jwks_client.py#L11

    I needed it for Auth0 to work.

    similar to #200 and #250

    opened by damelLP 11
  • How to access request object in get_token?

    How to access request object in get_token?

    I want to access request object in get_token because I want to get company_id from the POST request and add into token claims.

    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    
        @classmethod
        def get_token(cls, user):
            token = super().get_token(user)
    
            # Add custom claims
            token['company_id'] = request.POST['company_id']
    
            return token
    
    opened by rajasimon 10
  • request.user is always Anomynous

    request.user is always Anomynous

    I can post and generate a token and refresh pair, I can refresh the token, I can verify the token. but when I try to read some login-needed-content, it says that the request.user is an Anonymous user.

    Here are my codes that has changed for simplejwt in settings.py

    REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) }

    `SIMPLE_JWT = {

    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=15), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None,

    'AUTH_HEADER_TYPES': ('Bearer',),
    'USER_ID_FIELD': 'id',
    'USER_ID_CLAIM': 'user_id',
    
    'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
    'TOKEN_TYPE_CLAIM': 'token_type',
    
    'JTI_CLAIM': 'jti',
    
    'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
    'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=15),
    

    }`

    opened by lynkas 10
  • Revoke refresh token if password is changed

    Revoke refresh token if password is changed

    If the user changes his/her password, the old refresh token can still be used to generate new access tokens.

    How to make refresh tokens invalid if username or password is changed

    opened by adwait-thattey 10
  • "Token is invalid or expired" error because cryptography package was not installed

    We are using a microservice architecture where we create our jwt tokens in a different service. We added today django-rest-framework-simplejwt for verifying jwt tokens in one of our django services. While adding this we were faced with the error message that the Token is invalid or expired. We are using RS256 and checked that the token and public key were valid. We tracked down the issue and found out that PyJWT raised an issue that RS256 algorithm does not exist.

    This was because the cryptography was not installed in the virtualenv. Also, we are using pip-tools for dependency management. After adding cryptography to the dependencies manually it now works fine.

    Did anyone else faced the same issue?

    enhancement 
    opened by thacoon 10
  • Implement LastLogin when user is succesfully logged in on validation

    Implement LastLogin when user is succesfully logged in on validation

    I think this functionality should come with the built in serializer since it just has to update the User.last_login column of the User model.

    Also extending the view serializer and re-creating new routes just to add 1 or 2 lines of code that would easily cover the use case of many people is too much of a work for something that could come with the built-in serializer

    opened by DrJfrost 10
  • Validate without database query

    Validate without database query

    For me the attractive feature of JWT is the ability to provide validation of a request without the need to make a database query.

    However, in the current implementation here, it appears that the related User model is queried and populated on every request.

    https://github.com/SimpleJWT/django-rest-framework-simplejwt/blob/master/rest_framework_simplejwt/authentication.py#L100-L117

    Is it feasible to remove this query, or is the User object required by the underlying django-rest-framework?

    question 
    opened by monkut 10
  • AUTH_USER_MODEL used before it is installed

    AUTH_USER_MODEL used before it is installed

    I'm trying to integrate this package into my API and it's giving me problems when I'm trying to run the server. I get the error

    django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed
    

    user.User refers to a custom User model written to hold some extra information. The error occurs when in state.py you call get_user_model() to get the User model. I think it's called before the INSTALLED_APPS are actually installed, which is a problem. I even tried moving the user app to be before all the other apps being installed, including rest_framework and api, but that didn't fix anything. Any ideas? I'm happy to post code, but I don't know exactly what you want. I did exactly what the README says to do. Thanks in advance!

    opened by eabrouwer3 10
  • Setup initial PyJWT 1.7.1 support

    Setup initial PyJWT 1.7.1 support

    Supporting older PyJWT support due to many old open source packages.

    Fixes #464

    • Tests will need to be... repetitive.
    enhancement 
    opened by Andrew-Chen-Wang 0
  • Allow User creation after token validation.

    Allow User creation after token validation.

    Hi ! I've successfully set up a Django project that validates JWTs from AWS Cognito using the JWK_URL setting.

    I ran into a problem though, which is the fact that users making requests to my API don't necessarily have a corresponding record in the local User table, so JWTAuthentication.get_user runs into problems. I would like to have the chance to create these users.

    I ended up subclassing JWTAuthentication and made it work by overriding the get_user method.

    I think this could be a good improvement to the library, and is probably a common requirement from users in positions like mine (using external auth).

    With a bit of guidance as to how exactly this could/should be implemented, I'd be glad to work on a small PR.

    enhancement 
    opened by cristobalmackenzie 2
  • Allow other header claims in tokens

    Allow other header claims in tokens

    As defined in RFC7515, section 4.1, tokens can include several more header claims than just typ and alg as allowed from this.

    I have tried to include a kid one as I use signed token but I couldn't.

    Using pyjwt I was able to add it to the token string but when I called RefreshToken(token) constructor it removed all custom headers.

    I have checked in the doc and nothing seems to cover this use case.

    I haven't digged much in the code though.

    As for kid claim, I suggest to include it by default in header when the token is signed.

    (AuthLib documentation for reference)

    This is somehow related to #491 as kid might be useful when combined with JWK endpoint.

    enhancement 
    opened by 73VW 6
  • Update CHANGELOG.md for v5.1.0

    Update CHANGELOG.md for v5.1.0

    unfortunately, I couldn't check pyjwt 1.7.1 version

    opened by 2ykwang 1
  • FOREIGN KEY constraint failed

    FOREIGN KEY constraint failed

    I think there is an issue to get the RefreshToken. refresh = RefreshToken.for_user(newUserObj) but it's works when i tried with a previously created user object. refresh = RefreshToken.for_user(previouslyCreatedUserObj) works fine.

    question needs investigation 
    opened by AyemunHossain 1
  • How to archive the two cookie split with simple jwt?

    How to archive the two cookie split with simple jwt?

    Hello, I am trying to make a solution with this approach: https://medium.com/lightrail/getting-token-authentication-right-in-a-stateless-single-page-application-57d0c6474e3

    Jump to the "section/header": The Cookie Split

    What is the right way to do this? Would it be to override the post method in TokenObtainPairView ? And create the cookies I want? I guess I would need to create a middleware, to combine the two cookies into the "right" header, and then it should work with the way simplejwt work today. So my question is basically how to set the cookies.

    opened by jakobdo 0
  • If the blacklist app is enabled mark rotated refresh tokens as outstanding

    If the blacklist app is enabled mark rotated refresh tokens as outstanding

    The token blacklisting itself works without this (the OutstandingToken object will be created when adding a token to the blacklist), but the list of outstanding tokens would very quickly get out of date in the presence of refresh token rotation, and be unusable for any other purpose (for example being able to tell which users have valid outstanding tokens).

    needs investigation 
    opened by vainu-arto 0
  • Is there a way to generate a token for a user with a custom serializer?

    Is there a way to generate a token for a user with a custom serializer?

    I see that https://django-rest-framework-simplejwt.readthedocs.io/en/latest/creating_tokens_manually.html provides a way to create tokens manually, which is awesome!

    However, it looks like https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html can be used to override the views only and not so much this token generation method?

    I need to generate a token with custom claims, is this possible using this framework?

    question 
    opened by taylornelson-outside 1
  • Is there a way to expose an endpoint for JWK?

    Is there a way to expose an endpoint for JWK?

    I'm looking to expose the JWT public keys as an endpoint, so things like Nginx or Envoy can verify the token. I know this framework adds in /token/verify endpoints so that the entire token can be passed and verified; but some of these seem to prefer grabbing the keys and validating themselves.

    I see the jwk_url in the docs, but that seems like an optional thing to embed this URL into the token itself. But perhaps i'm missing something?

    Thanks for the help.

    enhancement question 
    opened by justincely 7
  • Allow None for JTI_CLAIM and TOKEN_TYPE_CLAIM

    Allow None for JTI_CLAIM and TOKEN_TYPE_CLAIM

    This is the only way I could get it working with an Auth0 JWT, which has neither 'jti' nor 'token_type'.

    needs investigation 
    opened by Jaza 11
Releases(v5.0.0)
  • v5.0.0(Oct 13, 2021)

    What's Changed

    • Set BLACKLIST_AFTER_ROTATION by default to False by @mohmyo in https://github.com/jazzband/djangorestframework-simplejwt/pull/455
    • Repair generation of OpenAPI with Spectacular by @robrichter in https://github.com/jazzband/djangorestframework-simplejwt/pull/452
    • updated import list by @rajan-blackboxes in https://github.com/jazzband/djangorestframework-simplejwt/pull/459
    • Add blacklist view to log out users by @hodossy in https://github.com/jazzband/djangorestframework-simplejwt/pull/306
    • Add "iat" claim to token by @mizvyt in https://github.com/jazzband/djangorestframework-simplejwt/pull/192
    • Remove verify from jwt.decode() to follow PyJWT v2.2.0. by @dajiaji in https://github.com/jazzband/djangorestframework-simplejwt/pull/472
    • Update CHANGELOG for v4.9.0 (#472) by @felippem in https://github.com/jazzband/djangorestframework-simplejwt/pull/476

    New Contributors

    • @mohmyo made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/455
    • @robrichter made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/452
    • @rajan-blackboxes made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/459
    • @hodossy made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/306
    • @mizvyt made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/192
    • @dajiaji made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/472
    • @felippem made their first contribution in https://github.com/jazzband/djangorestframework-simplejwt/pull/476

    Full Changelog: https://github.com/jazzband/djangorestframework-simplejwt/compare/v4.8.0...v5.0.0

    Source code(tar.gz)
    Source code(zip)
  • v4.8.0(Aug 19, 2021)

    Version 4.8.0

    • Add integration instructions for drf-yasg (#145)
    • Verify Serializer Should Honour Blacklist (#239)
    • Added missing import in getting_started docs (#431)
    • Use import_string for token_backend (#435)
    • Add JWKS support (#437)
    • Use pathlib instead of open in setup.py (#339)
    • Optimize default_user_authentication_rule (#441)
    • Add Leeway option to decode (#445)
    Source code(tar.gz)
    Source code(zip)
  • v4.7.2(Jul 6, 2021)

Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 848 Feb 21, 2022
JSON:API support for Django REST framework

JSON:API and Django REST framework Overview JSON:API support for Django REST framework Documentation: https://django-rest-framework-json-api.readthedo

null 983 Feb 18, 2022
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 712 Feb 11, 2022
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.1k Feb 23, 2022
Country-specific Django helpers, to use in Django Rest Framework

django-rest-localflavor Country-specific serializers fields, to Django Rest Framework Documentation (soon) The full documentation is at https://django

Gilson Filho 17 Jul 22, 2021
Document Web APIs made with Django Rest Framework

DRF Docs Document Web APIs made with Django Rest Framework. View Demo Contributors Wanted: Do you like this project? Using it? Let's make it better! S

Manos Konstantinidis 616 Dec 18, 2021
Django Ninja is a web framework for building APIs with Django and Python 3.6+ type hints.

?? Fast, Async-ready, Openapi, type hints based framework for building APIs

Vitaliy Kucheryaviy 2.6k Feb 25, 2022
Automated generation of real Swagger/OpenAPI 2.0 schemas from Django REST Framework code.

drf-yasg - Yet another Swagger generator Generate real Swagger/OpenAPI 2.0 specifications from a Django Rest Framework API. Compatible with Django Res

Cristi Vîjdea 2.6k Feb 21, 2022
Introduction to Django Rest Framework

Introduction to Django Rest Framework This is the repository of the video series Introduction to Django Rest Framework published on YouTube. It is a s

Simple is Better Than Complex 13 Feb 2, 2022
DRF-extensions is a collection of custom extensions for Django REST Framework

Django REST Framework extensions DRF-extensions is a collection of custom extensions for Django REST Framework Full documentation for project is avail

Gennady Chibisov 1.3k Feb 20, 2022
Generate Views, Serializers, and Urls for your Django Rest Framework application

DRF Generators Writing APIs can be boring and repetitive work. Don't write another CRUDdy view in Django Rest Framework. With DRF Generators, one simp

Tobin Brown 314 Feb 10, 2022
Swagger Documentation Generator for Django REST Framework: deprecated

Django REST Swagger: deprecated (2019-06-04) This project is no longer being maintained. Please consider drf-yasg as an alternative/successor. I haven

Marc Gibbons 2.6k Feb 21, 2022
Recursive Serialization for Django REST framework

djangorestframework-recursive Overview Recursive Serialization for Django REST framework This package provides a RecursiveField that enables you to se

null 315 Feb 17, 2022
Dropdown population implementation for Django REST Framework

drf-dropdown Dropdown population implementation for Django REST Framework Usage Add DropdownView to API URL # urls.py import dropdown urlpatterns = [

Preeti Yuankrathok 2 Jan 21, 2022
simple api build with django rest framework

Django Rest API django-rest-framework Employees management simple API in this project wrote test suites for endpoints wrote simple doc string for clas

OMAR.A 0 Jan 12, 2022
Simple Crud Api With Django Rest Framework

SIMPLE CRUD API WITH DJANGO REST FRAMEWORK Django REST framework is a powerful and flexible toolkit for building Web APIs. Requirements Python 3.6 Dja

kibet hillary 1 Dec 2, 2021
BloodDonors: Built using Django REST Framework for the API backend and React for the frontend

BloodDonors By Daniel Yuan, Alex Tian, Aaron Pan, Jennifer Yuan As the pandemic raged, one of the side effects was an urgent shortage of blood donatio

Daniel Yuan 1 Oct 24, 2021
Built on Django Rest Framework, to provide with command execution on linux terminal

Built on Django Rest Framework, to provide with command execution on linux terminal

null 1 Oct 31, 2021