Giter Site home page Giter Site logo

styria-digital / django-rest-framework-jwt Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jpadilla/django-rest-framework-jwt

189.0 7.0 57.0 1.33 MB

JSON Web Token Authentication support for Django REST Framework

Home Page: https://styria-digital.github.io/django-rest-framework-jwt/

License: MIT License

Python 100.00%

django-rest-framework-jwt's People

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

django-rest-framework-jwt's Issues

get_token_from_request can raise DjangoUnicodeDecodeError

Python 3.6 and Django 2.2 , if there is some strange authentication header like Bearer \x9d

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 493, in dispatch
    self.initial(request, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 410, in initial
    self.perform_authentication(request)
  File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 324, in perform_authentication
    request.user
  File "/usr/local/lib/python3.6/site-packages/rest_framework/request.py", line 220, in user
    self._authenticate()
  File "/usr/local/lib/python3.6/site-packages/rest_framework/request.py", line 373, in _authenticate
    user_auth_tuple = authenticator.authenticate(self)
  File "/usr/local/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 66, in authenticate
    token = self.get_token_from_request(request)
  File "/usr/local/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 91, in get_token_from_request
    authorization_header = force_str(get_authorization_header(request))
  File "/usr/local/lib/python3.6/site-packages/django/utils/encoding.py", line 69, in force_text
    raise DjangoUnicodeDecodeError(s, *e.args)
django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 7: invalid start byte. You passed in b'Bearer \x9d' (<class 'bytes'>)

how to regist jwt into router

hello, i use redoc for auto documentation using generic view set

my question is, how to regis jwt from rest_framework_jwt.views into drf_yasg.views router


schema_view = get_schema_view(
    openapi.Info(
        title="API",
        default_version='v1',
        description="Welcome to the documentation",
        terms_of_service="https://xxx",
        contact=openapi.Contact(email="xxxx"),
        license=openapi.License(name="xxxx"),
    ),
    public=False,
    permission_classes=(permissions.AllowAny,),
)


router = DefaultRouter()
router.register('auth', GenericsTokenViewSet, basename='auth')
router.register('jwt', ` ad jwt view set here`, basename='jwt')   <----------------- here

How to set primary key for "blacklist.BlacklistedToken"

I included 'rest_framework_jwt.blacklist' in INSTALLED_APPS as mentioned in the official documentation. However, I am getting the following warning about auto-created primary key every time I run or migrate the DRF app:

blacklist.BlacklistedToken:` (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
	HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlacklistedTokenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'

Simply removing the blacklist app from INSTALLED_APPS will no longer show this warning, but wanted to make sure to avoid any DB issues. How can I manually configure the primary key for the blacklist app?

Status Code in Swagger are wrong

I have a Django project using this module and it works very vell, thanks for all of that! When writing unit tests I realized that the documentation states, that I should get 201 as a status code from /verify, /refresh and the original post method, which makes sense as 201 is the default return code for post and means "object created". But when executing all of the methods, I got 200 for "OK" back, which is also fine - but not documented.

Could someone verify this problem, I would try to work on a solution if it isn't just me. Also, which one should it be?

Install instructions missing "rest_framework_jwt" for installed apps

I tend to follow the installation instructions and had this working before. Now after sometime I tried to use this a different project and it refused to work even though I had followed the instructions.

I had to check an old project to see how I solved it and it turns out that I forgot to add "rest_framework_jwt" in the installed APPS.

Could you maybe add this to you docs for the settings file? Usually when following instructions, it would be good if the thing works without issues.

Blacklisted tokens can still be refreshed

If you configure an app to allow blacklisting tokens and turn JWT_ALLOW_REFRESH on, then you can still operate the refresh endpoint using a blacklisted token, which allows you to side-step the fact that the token is invalidated.

Tests with settings monkeypatches failing

It looks like all tests that are using monkeypatch to make changes to the api_settings recently started to fail. I tried a bit to fix this for the PRs I just opened, but am not completely sure what is causing this, might be some update in a dependency (?).

The only thing related I could find for this is the following issue in django-rest-framework:

encode/django-rest-framework#7120

RFC: Support for multiple key IDs

Before starting any development work, I would like to ask for opinions/advise on the following feature idea:
Seamless changes to the signing key of a JWT, be it symmetrical or asymmetrical, requires a rollover procedure where consumers start to accept a new key before issuers create any tokens signed by it. While it would be possible to support such rollover with just a second key to try (usually called a transition secret or key), using JSON Web Key (JWK) IDs (kid) appears to be the cleaner solution:
a kid (key id) parameter imforms consumers about which (known) key to use for validating a token.

Notice that this is particularly relevant in scenarios where a single JWT/JWS is used by multiple applications which need to be coordinated for secret/key rollover.

While complete JSON Web Signature (JWS) support would include many more JOSE header values, I would suggest to only add

  • support for the kid paramter
  • support for multiple public keys / secrets to accept, identified by a kid
  • stick to a single public key / secret to use for issuing tokens, which also needs to be identified by a kid

Opinions?

Travis deploy stage fails to upload distribution

It seems that changing the deploy token didn't quite do the trick.

  0%|          | 0.00/25.8k [00:00<?, ?B/s]
 31%|###1      | 8.00k/25.8k [00:00<00:00, 70.0kB/s]
100%|##########| 25.8k/25.8k [00:00<00:00, 99.1kB/s]
NOTE: Try --verbose to see response content.
HTTPError: 403 Client Error: Invalid or non-existent authentication information. 
See https://pypi.org/help/#invalid-auth for details for url: https://upload.pypi.org/legacy/
PyPI upload failed.

travis_fold:end:dpl.3
failed to deploy

Could someone with the authentication credentials please troubleshoot it? It's OK to create a couple of empty patch releases. We can always delete them once it's working, including the packages from PyPI.

Migrations fail on MySQL

The migrations for the new blacklist app fail because TextField can't have a unique constraint in MySQL: https://docs.djangoproject.com/en/2.2/ref/databases/#textfield-limitations . It fails with:

BLOB/TEXT column 'token' used in key specification without a key length

For now we can downgrade to 0.14.0 as we don't need the blacklist functionality yet, but this is a blocker for upgrading until not only a new migration fixes the problem, but the existing migration changes to not blow up on MySQL.

Async Support

I'm dealing with a problem that seems related with this library (full traceback at the end)

 File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/authentication.py", line 86, in authenticate
    if BlacklistedToken.is_blocked(token, payload):
  File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/blacklist/models.py", line 58, in is_blocked
    return BlacklistedToken.objects.filter(query).exists()

My project is web application that receives astronomical images and automatically triggers the reduction process and displays them in the browser.
So the django views run synchronously with gunicorn as the server. There is also a websocket service that runs independently with daphne (async). Same container and django app though. The problem happens when the backend sends a notification via websockets that a new file has "arrived" into the system and the frontend (react) requests /gsp/api/files/ to get an updated list of files.

I was wondering if there are plans to support async requests in the near future.

Here is the full traceback.

ERROR [2021-11-03 12:43:53,125] log Internal Server Error: /gsp/api/files/
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch
    self.initial(request, *args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial
    self.perform_authentication(request)
  File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication
    request.user
  File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user
    self._authenticate()
  File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 380, in _authenticate
    user_auth_tuple = authenticator.authenticate(self)
  File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/authentication.py", line 86, in authenticate
    if BlacklistedToken.is_blocked(token, payload):
  File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/blacklist/models.py", line 58, in is_blocked
    return BlacklistedToken.objects.filter(query).exists()
  File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 808, in exists
    return self.query.has_results(using=self.db)
  File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 552, in has_results
    return compiler.has_results()
  File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1145, in has_results
    return bool(self.execute_sql(SINGLE))
  File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql
    cursor = self.connection.cursor()
  File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner
    raise SynchronousOnlyOperation(message)
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

Paradox leading to non-usability: You can't refresh a token that's no longer there. Or am I misunderstanding this?

Using HttpOnly tokens for security. Let's say the token has 30 seconds of life with 90 minutes to renew -- using JWT_EXPIRATION_DELTA': timedelta(seconds=30) and JWT_REFRESH_EXPIRATION_DELTA': timedelta(minutes=90)

So I send my /token-auth request with a user and password. I receive a token back good for 30 seconds.

This is from the response header:

Set-Cookie: my-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJvbmVubWFnaWQrZmlsbXNpbnRsQGdtYWlsLmNvbSIsImlhdCI6MTU5ODQ3MzIyMiwiZXhwIjoxNTk4NDczMjUyLCJqdGkiOiI3YzEwZTJhMi0wZjQ0LTQ3NjAtOTg3MS0yMmNmNmM4MTI4ZTYiLCJ1c2VyX2lkIjoiNjEyODRjNDItYTdjOS00YWM1LWExZjYtMDY0YzNjOTI1OTVkIiwib3JpZ19pYXQiOjE1OTg0NzMyMjJ9.Y9DIw6ldGog-fsnMFph9ObmVQog1KWhTBjYxnM3u8N4; expires=Wed, 26 Aug 2020 20:20:52 GMT; HttpOnly; Max-Age=30; Path=/; SameSite=None; Secure

So I keep sending subsequent request during the 30 seconds, all is good. The request header reads:

Cookie: my-token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InJvbmVubWFnaWQrZmlsbXNpbnRsQGdtYWlsLmNvbSIsImlhdCI6MTU5ODQ3MzIyMiwiZXhwIjoxNTk4NDczMjUyLCJqdGkiOiI3YzEwZTJhMi0wZjQ0LTQ3NjAtOTg3MS0yMmNmNmM4MTI4ZTYiLCJ1c2VyX2lkIjoiNjEyODRjNDItYTdjOS00YWM1LWExZjYtMDY0YzNjOTI1OTVkIiwib3JpZ19pYXQiOjE1OTg0NzMyMjJ9.Y9DIw6ldGog-fsnMFph9ObmVQog1KWhTBjYxnM3u8N4

Now the 30 seconds expire.... the next request gets an understandable 401 but when I look at it's request header: The Token is gone, it's not used. It's been erased from Chrome.

Given that --- how can I use /token-refresh when it requires something I no longer have?

It's almost as if you are forced to renew it before it expires. But if this is the case, what's the point of having a longer JWT_REFRESH_EXPIRATION_DELTA?

Operation IDs correct?

Hi all,

Are this operation IDs correct? I feel like this should be token_create, token_refresh and token_verify. Or shouldn't they? I can create a PR for fixing this, if this is valid.

Screenshot 2020-12-27 at 11 34 57

TypeError('Expected a string value') when creating a key

Hi all,

I just moved from the original version to this fork. I am getting the following error:

Internal Server Error: /api/api-token-auth/
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework_jwt/views.py", line 28, in post
    serializer.is_valid(raise_exception=True)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 220, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "/usr/local/lib/python3.7/site-packages/rest_framework/serializers.py", line 422, in run_validation
    value = self.validate(value)
  File "/usr/local/lib/python3.7/site-packages/rest_framework_jwt/serializers.py", line 59, in validate
    'token': JSONWebTokenAuthentication.jwt_encode_payload(payload),
  File "/usr/local/lib/python3.7/site-packages/rest_framework_jwt/authentication.py", line 45, in jwt_encode_payload
    return api_settings.JWT_ENCODE_HANDLER(*args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/rest_framework_jwt/utils.py", line 130, in jwt_encode_payload
    return jwt.encode(payload, key, signing_algorithm, headers=headers, json_encoder=JSONEncoder).decode()
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jwt.py", line 65, in encode
    json_payload, key, algorithm, headers, json_encoder
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 113, in encode
    key = alg_obj.prepare_key(key)
  File "/usr/local/lib/python3.7/site-packages/jwt/algorithms.py", line 140, in prepare_key
    key = force_bytes(key)
  File "/usr/local/lib/python3.7/site-packages/jwt/utils.py", line 30, in force_bytes
    raise TypeError('Expected a string value')
TypeError: Expected a string value
[15/Feb/2021 13:49:46] "POST /api/api-token-auth/ HTTP/1.0" 500 133304

I uninstalled the old package and installed yours. Am I doing anything wrong?

Session management

What is the best practice for restrict sessions in django-rest-framework-jwt?
I mean admin restrict active session that means for example if userA login in computerA then when userA login from computerB, jwt in computerA is no longer valid and must login again.

New release with support for Django 3.2

Hi!
We are looking forward to using drf-jwt with Django 3.2

Required PR, for testing against the Django 3.2, was opened, but wasn't merged yet: #97
Is there any chance a new version will be bumped soon?

If any blockers with the release, I would be happy to help.

Thank you

Tests fail due to missing `django.utils.six`

______________ ERROR collecting tests/test_management_commands.py ______________
ImportError while importing test module '/home/travis/build/Styria-Digital/django-rest-framework-jwt/tests/test_management_commands.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
.tox/py36-dj30-drf311-codecov/lib/python3.6/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_management_commands.py:7: in <module>
    from django.utils.six import StringIO
E   ModuleNotFoundError: No module named 'django.utils.six'

This got removed in Django 3.0 and should be replaced with six. See also https://stackoverflow.com/a/59252857/320546

doesn't play well with other "Authorization"-header auth plugins

When the Authorization header is sent with a prefix other than the configured one (default Bearer, though I override it to be JWT in my app), drf-jwt raises an AuthenticationFailed. This means that authentication is completely stopped and other auth plugins don't get a chance to run.

My app uses both drf-jwt and DRF Token authentication, so when I switched from the old djangorestframework-jwt to this, my DRF Token authentication stopped working. The old djangorestframework-jwt properly returned None instead of raising AuthenticationFailed when the prefix wasn't one it expected.

[1.15.0] rest-framework-jwt breaks if blacklist app is not installed

New version forces users to have blacklist app installed even if the feature is not being used.

Eg. of failed test:

psycopg2.errors.UndefinedTable: relation "rest_framework_jwt_blacklistedtoken" does not exist
E LINE 1: SELECT (1) AS "a" FROM "rest_framework_jwt_blacklistedtoken"...

I assume the issue is here.

It wold be desirable to add a check if the app is installed and only run it if it is.

I can provide a fix if we agree on the solution ๐Ÿ˜„

maintenance status?

Dear people at Styria,
this comment suggests that there might not be an active maintainer for this package at the moment.
It would be helpful to get some quick feedback on the maintenance status. If you need any help, please say so.

Response body contains the auth token when enabling auth cookie

Hello,

I just tested this python module and found out that when you choose to send your token as a server cookie, the response body still contains the cookie (which is weird).

These screenshots are requests (using postman) to a demo project with the module installed for JWT authentication. As you can see, the auth token is both in the response body and response cookie :

Postman - Response body

image

Postman - Response headers

image

Edit :
I created a PR #99 to resolve this issue

Channels integration

Hello!

As all the other people that thought that the base repository was dead, I started working on my own version of the library, especially I found myself working on an integration with channels so that the same client is authenticated for web sockets too through cookies.

In short, I made a middleware that authenticates looking for the cookie with the jwt token since web sockets don't support headers (as far as I know).

Would you be interested in merging that feature?

I would be glad to use a library that has more contributors and to help of course.

Django 2.x

setup.py lists install requirements Django>=1.11,<2.0 , however this passes all tests on Django 2.2 at least, and pypi package django-restframework-jwt is known to work fairly well on Django 2.0 and 2.1 even now.

Is there any reason not to expand the support matrix to include Django 2.x, with .travis.yml/tox.ini matrixes covering those ?

I think that the lack of stated support for Django 2.x is one of the main reasons people are looking for a maintained drop-in replacement for pypi package django-restframework-jwt.

Doc does not contain section about decorators.

I am a beginner in Django and was looking at the docs for JWT authentication. I was scratching my head for a long time trying to figure where I went wrong, and found that I was not using decorators. The guide had no section about it.

JSONWebTokenSerializer.validate no longer fails if the user is not active

Hi, I am currently upgrading a project to use this fork from the original jpadilla version. So far the breaking changes have been clearly documented however I ran across this one which was not.

Previously ObtainJSONWebTokenView in jpadilla's version would raise ValidationError("User account is disabled.") if a non active user attempted to use the view and obtain a token. However now in the "Dropped support for drf<3.7, django<1.11. Refactored tests. " commit JSONWebTokenSerializer.validate was changed to no longer fail if the user was inactive.

The other views provided by this library use serializers like VerifyAuthTokenSerializer and RefreshAuthTokenSerializer which call check_user in their validate method which does raise for inactive users, however ObtainJSONWebTokenView uses JSONWebTokenSerializer which no longer does.

We can work around this change in our usage of drf-jwt for now, however:

  1. I'm not sure how intended this change in behaviour was, but perhaps there is a good reason for this change?
  2. It's a bit odd that the other views do check this but ObtainJSONWebTokenView does not.
  3. This is a breaking change from the old version and might trip up other users migrating.

If there is a good reason for this change then I am happy to open an MR updating the documentation to clearly state this change. However if not and we believe this should be fixed then I am also happy to fix it. To do so my initial thoughts are:

  1. Call check_user in JSONWebTokenSerializer.validate
  2. Create a new Serializer for ObtainJSONWebTokenView which calls check_user
  3. Copy the exact old check from jpadilla's JSONWebTokenSerializer.validate back into this libraries version

Let me know which if any of these you would prefer.

Thanks for the fork and all the new features!

custom JWT_RESPONSE_PAYLOAD_HANDLER negated by second call to view serializer

response_serializer = self.get_serializer(

The call to self.get_serializer at line 40 in BaseJSONWebTokenAPIView causes the payload created by api_settings.JWT_RESPONSE_PAYLOAD_HANDLER to be run back through the JSONWebTokenSerializer, effectively eliminating anything added to the payload by a custom handler other than the fields in JSONWebTokenSerializer.
For example, the custom payload handler, that I wrote and have been successfully using with the original GetBlimp package, uses "authentication_token", rather than "token" to return the token, and includes some additional pieces of data, but with the new view, the only thing returned by the response is "email".

custom username fields are not honored

I recently switched from the old djangorestframework-jwt to this package, and another thing I noticed is that the old package used to honor custom username fields by using get_user_model().USERNAME_FIELD (defined in get_username_field in compat.py). Funnily enough, drf-jwt defines a get_username_field() function in utils.py, but then doesn't use it, unconditionally assigning to username.

This ends up breaking my app because my authenticate stack requires my custom username field to be in the **kwargs that get passed to it, and tokens created with drf-jwt don't have that.

For now I am working around this problem by defining a custom JWT payload handler and renaming the key.

Future of django-rest-framework-jwt

Do you intend to actively maintain and develop this package?

I'm asking as I have projects which use this package and I have been maintaining a private version with additional bug fixes. If you intend to maintain this would you consider pull requests and do you intend to merge pull requests submitted to orginal repo (GetBlib)?

Axes Authentication backend

I use Axes as authentication backend, but when set AXES_FAILURE_LIMIT ==2 in first login attempt the obtain-jwt-token return
403, while it must return 400 and if I call obtain-jwt-token again, it must return 403.
I do not have this problem with https://github.com/jpadilla/django-rest-framework-jwt !

Deprecation Warnings In Django 3

We recently updated from Django 2 to Django 3 and are now seeing quite a few deprecation warnings regarding RemovedInDjango40Warning: django.utils.translation.ugettext() is deprecated in favor of django.utils.translation.gettext() coming from this package.

I believe this is caused by the try-catch block in compat.py being "reused" for multiple imports where the first line seems to fail in Django 3:

https://github.com/Styria-Digital/django-rest-framework-jwt/blob/master/src/rest_framework_jwt/compat.py#L12

It looks like url is not part of django.conf and therefore always raises ImportError:

https://docs.djangoproject.com/en/3.0/ref/urls/

I believe the following should fix the problem in compat.py, I'm just not completely sure if the middle block even makes sense or of it should be completely removed:

try:
    from django.urls import include
except ImportError:
    from django.conf.urls import include  # noqa: F401

try:
  from django.urls import url
except ImportError:
  from django.conf.urls import url

try:
    from django.utils.translation import gettext as gettext_lazy
except ImportError:
    from django.utils.translation import ugettext as gettext_lazy

documentation doesn't mention need of INSTALLED_APPS

I just switched from djangorestframework-jwt to this package, and one of the things I ran into was this error:

RuntimeError: Model class rest_framework_jwt.blacklist.models.BlacklistedToken doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

I had to add rest_framework_jwt to INSTALLED_APPS in order for my code to work. This isn't mentioned anywhere in the documentation.

Documentation to use Blacklist

Hi !

I'm triing to set up my first rest api with your work.
I want to make a /logout to blacklist the token but I don't how to use ?

The documentation is not very easy to understand in the part of blacklisting.

Thanks a lot for your job !

Blacklisting/revoking JWTs

If a user changes its authentication credentials, e.g. its password, the old token is still valid and the user is not "logged out". This could be a potential security issue when users' accounts are concerned, at least until the tokens expire.

Could we implement a mechanism for revoking/blacklisting JWTs? django-rest-framework-simplejwt's approach could serve as a good starting point.

Anonymous Users

Greetings, im a bit unexperienced developer and i've been using the previoues version from which u have forked this and i've been trying to get it included in an e-commerce solution with anonynimous users.
However, since drf requires user model for token generation i've been unable to provide a proper view for people who just visit the site, returning empty content pages, and after exhausting my options on the last 3 days i havent found any suitable examples on how to approach this or even how to use the jwt_auth_cookie to bypass this problem, since the documentation refers the field usage but has no linky on how to use this field.
If possible could you get fix for anonymous users token generation or point me out a solution for this ?

Update documentation to add explicit instructions for installation

Please add explicit instructions to add both rest_framework_jwt and rest_framework_jwt.blacklist to your INSTALLED_APPS.

INSTALLED_APPS = [
  'rest_framework_jwt',
  'rest_framework_jwt.blacklist'
]

I've just spent hours tracking down an issue that was arising when running my tests. I was getting a red-herring error message when setting up my tests:

psycopg2.errors.UndefinedTable: relation "user_customuser" does not exist

Looking online, most people with this issue related it to having missing migrations. I checked and double-checked all my migrations for my apps and they were all there.

It was only after I ran my tests with -v 3 did I realise the issue was happening after trying to set up rest_framework_jwt:

...
Running pre-migrate handlers for application team
Running pre-migrate handlers for application user
Running pre-migrate handlers for application volume
Synchronizing apps without migrations:
  Creating tables...
    Creating table rest_framework_jwt_blacklistedtoken
    Running deferred SQL...
Traceback (most recent call last):
  File "/Users/timmyomahony/.virtualenvs/ci-api/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "user_customuser" does not exist

The problem was that I didn't know about the blacklist app within the project, therefore it wasn't included in my INSTALLEDAPPS. Regardless, Django was looking for the table rest_framework_jwt_blacklistedtoken and was crashing everything.

compat.gettext_lazy is not using the lazy version

...
  File "/usr/lib/python3.8/site-packages/rest_framework/settings.py", line 177, in import_from_string
    return import_string(val)
  File "/usr/lib/python3.8/site-packages/django/utils/module_loading.py", line 17, in import_string
    module = import_module(module_path)
  File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/usr/lib/python3.8/site-packages/rest_framework_jwt/authentication.py", line 17, in <module>
    from rest_framework_jwt.blacklist.exceptions import (
  File "/usr/lib/python3.8/site-packages/rest_framework_jwt/blacklist/exceptions.py", line 8, in <module>
    class MissingToken(AuthenticationFailed):
  File "/usr/lib/python3.8/site-packages/rest_framework_jwt/blacklist/exceptions.py", line 10, in MissingToken
    msg = _('The token is missing.')
  File "/usr/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 92, in gettext
    return _trans.gettext(message)
  File "/usr/lib/python3.8/site-packages/django/utils/translation/trans_real.py", line 354, in gettext
    _default = _default or translation(settings.LANGUAGE_CODE)
  File "/usr/lib/python3.8/site-packages/django/utils/translation/trans_real.py", line 267, in translation
    _translations[language] = DjangoTranslation(language)
  File "/usr/lib/python3.8/site-packages/django/utils/translation/trans_real.py", line 154, in __init__
    self._add_installed_apps_translations()
  File "/usr/lib/python3.8/site-packages/django/utils/translation/trans_real.py", line 195, in _add_installed_apps_translations
    raise AppRegistryNotReady(
django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.

Patch OTW.

PyJWT 2.x not supported

Requirement is currently listed as PyJWT[crypto]>=1.5.2,<2.0.0, and 2.0.0 is now out. I've got a clash with another library that just wants >=2.0, and so would love to get compatibility for both (or just >2).

Refresh Token Issue

RefreshAuthTokenSerializer has bug in validate method.
In situation if token is expired, but still could be refreshed it returns an error saying "Token is expired", but is should not raise this error.

As I see, we are calling payload = _check_payload(token=token) which is responsible for raising this error.

One of many ways to fix it:

file loc: rest_framework_jwt.serializers._check_payload
def _check_payload(token):
      try:
          payload = JSONWebTokenAuthentication.jwt_decode_token(token)

=>

def _check_payload(token, *args, **kwargs):
      try:
          payload = JSONWebTokenAuthentication.jwt_decode_token(token, *args, **kwargs)

file loc:  rest_framework_jwt.serializers.RefreshAuthTokenSerializer.validate
payload = _check_payload(token=token)

=>

payload = _check_payload(token=token, check_jwt_verify_expiration=False)

file loc: rest_framework_jwt.utils.jwt_decode_token
def jwt_decode_token(token):
  options = {
        'verify_exp': api_settings.JWT_VERIFY_EXPIRATION,
     }

=>

def jwt_decode_token(token, check_jwt_verify_expiration=True):
  options = {
        'verify_exp': api_settings.JWT_VERIFY_EXPIRATION and check_jwt_verify_expiration,
     }

How to use verify_jwt_token with token in httpOnly cookie?

Hi,

I want to use httpOnly cookies for storing the token, which works already as expected, but the verify_jwt_token view expects the token being sent as payload in the body!?

Is there a way to verify a token passed as httpOnly cookie?

Django 4.0 Support

Django 4.0 dropped today which removed django.conf.urls.url(). It looks like we're getting an import error here and subsequently here e.g.

ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'url' from 'django.urls' (/usr/local/lib/python3.8/dist-packages/django/urls/__init__.py).

I did a bit of searching through the codebase and it looks like we could switch to re_path or path for this project but I'm not 100% sure. Wanted to file an issue to get the ball rolling on a solution.

Problems with Django 4 after install

After installing package (also in INSTALLED APPS) I cant run the project, still getting an error:

env/lib/python3.11/site-packages/rest_framework_jwt/blacklist/models.py", line 10, in
from rest_framework_jwt.settings import api_settings
ModuleNotFoundError: No module named 'rest_framework_jwt.settings'

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.