Validating auth0 with ariadne #724
Replies: 2 comments
-
Unless you want to have authentication as a schema directive, it would mostly likely happen when a protected endpoint of your application is hit (e.g. The project I work for uses a decorator to mark protected endpoints. It decodes the JWT from the request header and adds the data to the global context of the current request such that it can be retrieved from other points of the app (we use Flask but for Django there's probably a similar mechanism). Check out the implementation, hope it helps!
|
Beta Was this translation helpful? Give feedback.
-
Our graphql application sits behind a DRF view. Feel free to @ me if you have any questions! I can't seem to find the exact tutorial I followed, and searching for it now all the tutorials have slightly different solutions. I think it will be dependent on your needs, but here are some similar tutorials that might be helpful: https://dev.to/a_atalla/django-rest-framework-custom-jwt-authentication-5n5 # in core/views.py
@api_view(['POST'])
@permission_classes([AllowAny])
def graphql_api(request):
"""
Endpoint for graphql api.
Must include valid auth header.
"""
if not request.content_type.startswith('application/json'):
return HttpResponseBadRequest()
try:
data = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest()
success, result = graphql_sync(
schema,
data,
context_value={
'request': request,
},
debug=settings.DEBUG,
)
status_code = 200 if success else 400
return JsonResponse(result, status=status_code) # settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'core.authentication.CustomJSONWebTokenAuthentication',
),
}
JWT_AUTH = {
'JWT_PAYLOAD_GET_USERNAME_HANDLER': 'core.authentication_helpers.jwt_get_username_from_payload_handler',
'JWT_DECODE_HANDLER': 'core.authentication_helpers.jwt_decode_token',
'JWT_ALGORITHM': 'RS256',
# audience from auth0
'JWT_AUDIENCE': os.environ['JWT_AUDIENCE'],
# domain from auth0
'JWT_ISSUER': os.environ['JWT_ISSUER'],
'JWT_AUTH_HEADER_PREFIX': 'Bearer',
} # in core/authentication_helpers.py
def jwt_get_username_from_payload_handler(payload):
"""
Returns auth_id from jwt payload.
"""
auth_id = payload.get('sub')
return auth_id
def jwt_decode_token(token):
"""
Decodes JWT Token
"""
header = jwt.get_unverified_header(token)
jwks = requests.get(
'https://{}/.well-known/jwks.json'.format(JWT_ISSUER)).json()
public_key = None
for jwk in jwks['keys']:
if jwk['kid'] == header['kid']:
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
if public_key is None:
raise Exception('Public key not found.')
issuer = 'https://{}/'.format(JWT_ISSUER)
return jwt.decode(
token,
public_key,
audience=JWT_AUDIENCE,
issuer=issuer,
algorithms=['RS256']) # in core/authentication.py
from django.contrib.auth import get_user_model
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.compat import gettext_lazy as _
UserModel = get_user_model()
class CustomJSONWebTokenAuthentication(JSONWebTokenAuthentication):
"""
Overrides Rest Framework authentication logic.
"""
def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's auth_id
"""
auth_id = self.jwt_get_username_from_payload(payload)
if not auth_id:
msg = _('Invalid payload.')
raise exceptions.AuthenticationFailed(msg)
try:
UserModel = get_user_model()
user = UserModel.objects.get(auth_id=auth_id)
except UserModel.DoesNotExist:
return None
if not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
return user |
Beta Was this translation helpful? Give feedback.
-
Hey guys I'm new to python and Django especially. Im making a django/Next project and I've been stuck on authentication. I decided to utilize
auth0
but I'm not sure how to validate the token. I see an example fordjango drf
in the link below but I cant find help online to implement the same thing using ariadne/django.link: https://auth0.com/docs/quickstart/backend/django
Beta Was this translation helpful? Give feedback.
All reactions