usama0121 / ariadne-jwt Goto Github PK
View Code? Open in Web Editor NEWJSON Web Token (JWT) authentication for Ariadne Django
License: MIT License
JSON Web Token (JWT) authentication for Ariadne Django
License: MIT License
Running ariadne-jwt 0.1.7 with Django 4.0 throws the following exception:
[...]
File "[...]/python3.10/site-packages/ariadne_jwt/refresh_token/models.py", line 10, in <module>
from . import managers, signals
File "[...]/python3.10/site-packages/ariadne_jwt/refresh_token/signals.py", line 3, in <module>
refresh_token_revoked = Signal(providing_args=['refresh_token'])
TypeError: Signal.__init__() got an unexpected keyword argument 'providing_args'
Indeed the providing_args
argument was deprecated in Django 3.1. As this argument is described as “purely documentational” it seems that removing it should be harmless.
Do you have any plans to implement this?
If I use the authToken
mutation as explained in the README.
jwt_schema
defines :
type TokenAuth {
token: String
refresh_token: String
payload: GenericScalar
}
If I login, I receive this:
{
"data": {
"tokenAuth": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQ3NjE1Nzk3LCJvcmlnSWF0IjoxNjQ3NjEyMTk3fQ.j5BQ-KhQeqwJv0hjMTYDP2D4Py1uIKcJpPlSeCR8qmg",
"refresh_token": null,
"payload": null
}
}
}
refresh_token
and payload
are always null ....
In an attempt to refresh the token, I tried the refreshToken
mutation and passed my current token, which worked and got me this response:
{
"data": {
"refreshToken": {
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjQ3NjE1OTA0LCJvcmlnSWF0IjoxNjQ3NjEyMTk3fQ.hwH4EruJ_21_XjmEb42VPpgpuzprWr29654OG-C1ELE",
"refresh_token": null,
"payload": {
"username": "admin",
"exp": 1647615904,
"origIat": 1647612197
}
}
}
Again, refresh_token
is null as well
What's the idea behind those two? I expected to get a token and a refresh token as result of the tokenAuth
mutation and that I need to use the refresh token with the refreshToken
mutation in order to receive a new pair of tokens!?
Can you please bring some light into this?
Also I wonder how to logout a user? Simply delete the token on the client side?
I have this config:
GRAPHQL_JWT = {
"JWT_AUTH_HEADER_PREFIX": "Token",
"JWT_EXPIRATION_DELTA": timedelta(seconds=60 * 5),
"JWT_VERIFY_EXPIRATION": True,
"JWT_LONG_RUNNING_REFRESH_TOKEN": True,
"JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=7),
}
when I try to verify or refresh the token the endpoint always says:
{
"error": {
"errors": [
{
"message": "Signature has expired"
}
]
}
}
Is something missing?
getting this error after making one request using the token.
so I keep refreshing the token one every request.
Thanks for creating this package!
Please bare with me as I am new to python and Django especially but I have this issue that sometimes when I runserver I get this error:
Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 125, in check_dependencies if not _contains_subclass('django.contrib.messages.middleware.MessageMiddleware', settings.MIDDLEWARE): File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/contrib/admin/checks.py", line 41, in _contains_subclass candidate_cls = import_string(path) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/chuksgrinage/.pyenv/versions/3.9.6/lib/python3.9/site-packages/ariadne_jwt/middleware.py", line 6, in <module> from .utils import get_authorization_header File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 989, in _find_and_load_unlocked KeyError: 'ariadne_jwt'
I cant figure this out and I've searched all over for a solution but nothing helped. My last resort was to reach out to the creator directly. Any help would me greatly appreciated.
I found out that the long running refresh tokens are not revoked after rotation, leading to multiple valid long lived refresh tokens.
I would like to change the default JWT expiration time, but I can't find anything in the documentation to do it. Additionally, the settings.py
for this package doesn't really expose anything to change settings conveniently. Am I missing something here or is this a feature that has not been implemented yet?
Hi!
It's possible create a token and refresh it without save it in the database? Any idea or implementation?
Thanks!
thats the error I am getting.
It looks like in graphql-core
version 3.2.0 the MAX_INT
and MIN_INT
attributes were renamed to GRAPHQL_MAX_INT
and GRAPHQL_MIN_INT
, respectively. This breaks the import in ariadne_jwt/scalar.py
.
Workaround: the project including ariadne-jwt
should add a requirement for graphql-core<3.2.0
. The last working version is 3.1.7.
Changed lines in graphql-core
as of version 3.2.0:
https://github.com/graphql-python/graphql-core/blob/66e5ae9d4936c3d28dfe00290d8316f2acdefd30/src/graphql/type/scalars.py#L35
https://github.com/graphql-python/graphql-core/blob/66e5ae9d4936c3d28dfe00290d8316f2acdefd30/src/graphql/type/scalars.py#L38
i am porting the django-graphql-auth into my project based on ariadne, i need some help in decorators as i need to use email for login instead of username
When trying to use code like the following:
@query.field("accounts")
@login_required
@staff_member_required
def resolve_accounts(*_):
return Account.objects.all()
It results in a stack trace like the following:
IndexError: tuple index out of range
File "graphql/execution/execute.py", line 617, in resolve_field
result = resolve_fn(source, info, **args)
File "ariadne_jwt/decorators.py", line 27, in wrapper
info = args[f.__code__.co_varnames.index('info')]
GraphQLError: tuple index out of range
GraphQL request:2:3
1 | {
2 | accounts {
| ^
3 | name
File "graphql/execution/execute.py", line 617, in resolve_field
result = resolve_fn(source, info, **args)
File "ariadne_jwt/decorators.py", line 27, in wrapper
info = args[f.__code__.co_varnames.index('info')]
I've traced it to the context
decorator that is used inside the user_passes_test
decorator. I do not know what info = args[f.__code__.co_varnames.index('info')]
accomplishes, but there is no "info" value in the co_varnames
of staff_member_required
which causes the exception.
Hi there,
Thanks for creating this package. I noticed that the package on PyPi misses the requirments.txt, which causes the install to fail. Installing it via pip from GitHub works though.
Cheers
#8 5.180 ERROR: Command errored out with exit status 1: #8 5.180 command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-resolver-c833913s/ariadne-jwt/setup.py'"'"'; __file__='"'"'/tmp/pip-resolver-c833913s/ariadne-jwt/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-q69q_jk3 #8 5.180 cwd: /tmp/pip-resolver-c833913s/ariadne-jwt/ #8 5.180 Complete output (5 lines): #8 5.180 Traceback (most recent call last): #8 5.180 File "<string>", line 1, in <module> #8 5.180 File "/tmp/pip-resolver-c833913s/ariadne-jwt/setup.py", line 21, in <module> #8 5.180 with open('requirements.txt', 'r') as fin: #8 5.180 FileNotFoundError: [Errno 2] No such file or directory: 'requirements.txt'
Hey! Thanks for writing this; I am a huge fan of Ariadne, Django, and JWTs.
I would love to hack on this project a bit, but as I generally use pytest
, I cannot for the life of me figure out how to run the unit tests.
I have tried in the root folder:
$ DJANGO_SETTINGS_MODULE=tests.settings python -m unittest # and got
EEEEEEEEEEEEEEEEE
======================================================================
ERROR: ariadne_jwt.refresh_token.admin (unittest.loader._FailedTest)
ImportError: Failed to import test module: ariadne_jwt.refresh_token.admin
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
======================================================================
ERROR: setUpClass (tests.refresh_token.test_commands.ClearTokensTests)
django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value.
and a total of 17 errors (all based on these two).
Adding 'NAME': ':memory:',
to tests/settings.py
gets rid of the ImproperlyConfigured
, but gives me 41 AppRegistryNotReady
errors.
Could you let me know how to run those tests (or better yet, add that to the README
)? Thanks!
PS: I have a number of ideas and suggestions. Is there a more direct way of communicating with you (e.g. discord) or would you prefer that I open issues for them?
Hi everyone,
No exactly an issue, but need help with setup.
Trying to get a new token from username and password and it keep returning as the credentials are not valid.
query
mutation tokenAuth {
tokenAuth(username:"[email protected]",
password:"foorpass") {
token
}
}
error
"stacktrace": [
"Traceback (most recent call last):",
" File \"/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/graphql/execution/execute.py\", line 617, in resolve_field",
" result = resolve_fn(source, info, **args)",
" File \"/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/ariadne_jwt/decorators.py\", line 89, in wrapper",
" raise exceptions.JSONWebTokenError(",
"ariadne_jwt.exceptions.JSONWebTokenError: Please, enter valid credentials"
],
"context": {
"root": "None",
"password": "'foorpass'",
"kwargs": "{'username': '[email protected]'}",
"on_resolve": "<function tok...t 0x1190eda20>",
"username": "None",
"user": "None",
"info": "GraphQLResolv... 0x103b9e9e0>)",
"f": "<function res...t 0x104154550>"
}
}
}
}
]
I have a custom user model, but USERNAME_FIELD is set to be 'email' and running the lambda function (the one setting JWT_PAYLOAD_GET_USERNAME_HANDLER) by hand it's return 'email'.
I also tried to login in Django base application first, but with no luck, it's also not recognizing the logged user.
Can anyone help me understand what's going on?
Hi,
First of all thanks for your package!
I can get the JTW token authorisation working with normal queries. However when decorate the resolver method of a subscription with login_required
decorator i run into an error:
Traceback (most recent call last):
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 623, in resolve_field_value_or_error
result = resolve_fn(source, info, **args)
File "/Users/erik/.virtualenvs/firewallautomation/src/ariadne-jwt/ariadne_jwt/decorators.py", line 28, in wrapper
return func(info.context, *args, **kwargs)
File "/Users/erik/.virtualenvs/firewallautomation/src/ariadne-jwt/ariadne_jwt/decorators.py", line 40, in wrapper
if test_func(context.get('request').user):
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/starlette/requests.py", line 146, in user
assert (
AssertionError: AuthenticationMiddleware must be installed to access request.user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 340, in execute_operation
result = (
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 433, in execute_fields
result = self.resolve_field(
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 604, in resolve_field
return self.complete_value_catching_error(
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 681, in complete_value_catching_error
self.handle_field_error(error, field_nodes, path, return_type)
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 696, in handle_field_error
raise error
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 667, in complete_value_catching_error
completed = self.complete_value(
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 733, in complete_value
raise result
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/graphql/execution/execute.py", line 623, in resolve_field_value_or_error
result = resolve_fn(source, info, **args)
File "/Users/erik/.virtualenvs/firewallautomation/src/ariadne-jwt/ariadne_jwt/decorators.py", line 28, in wrapper
return func(info.context, *args, **kwargs)
File "/Users/erik/.virtualenvs/firewallautomation/src/ariadne-jwt/ariadne_jwt/decorators.py", line 40, in wrapper
if test_func(context.get('request').user):
File "/Users/erik/.virtualenvs/firewallautomation/lib/python3.9/site-packages/starlette/requests.py", line 146, in user
assert (
graphql.error.graphql_error.GraphQLError: AuthenticationMiddleware must be installed to access request.user
The subscriptions is build using the Django-channels setup in the documentation. Both MIDDLEWARE and AUTHENTICATION_BACKENDS are properly configured.
Debugging shows that the code is trying to use context.get('request').user
.
When i don't use the login_required
decorator and have a look at the info.context["request"] using a breakpoint in the resolver the request is a starlette.websockets.WebSocket
object.
Accessing the user
property of this WebSocket object results in the same AssertionError: AuthenticationMiddleware must be installed to access request.user
error.
Any advice on how to get the login_required
decorator working with a subscription resolver method?
Thanks in advance!
Regards,
Erik
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.