Last active
January 16, 2020 16:35
-
-
Save dmutende/df91112682916490227d59a80dcfd39f to your computer and use it in GitHub Desktop.
Warpping GraphQL endpoints with Django OAuth2 Toolkit's ProtectedResourceView to secure them using OAuth2.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- create a .py file with 2 classes (OAuth2ProtectedResourceMixin and OAuth2ProtectedGraph). see 'utils.py' file | |
- then in your Django's 'urls.py', wrap the graphql endpoint. see 'urls.py. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# some other code | |
from utils import OAuth2ProtectedGraph | |
# some other code | |
urlpatterns = [ | |
# some other code | |
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), | |
url(r'^evr/graph', csrf_exempt(OAuth2ProtectedGraph.as_view(graphiql=True, schema=schema))), | |
# some other code | |
] | |
# some other code |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from oauth2_provider.views import ProtectedResourceView | |
from oauth2_provider.views.mixins import ProtectedResourceMixin | |
from rest_framework import status | |
from graphene_django.views import GraphQLView | |
from rest_framework.utils import json | |
class OAuth2ProtectedResourceMixin(ProtectedResourceView): | |
def dispatch(self, request, *args, **kwargs): | |
print(request.method, request) | |
# let preflight OPTIONS requests pass | |
if request.method.upper() == "OPTIONS": | |
return super(ProtectedResourceMixin, self).dispatch(request, *args, **kwargs) | |
# check if the request is valid and the protected resource may be accessed | |
valid, r = self.verify_request(request) | |
if valid: | |
request.resource_owner = r.user | |
return super(ProtectedResourceMixin, self).dispatch(request, *args, **kwargs) | |
else: | |
message = {'evr-api': | |
{'errors': ['Authentication failure']}} | |
return HttpResponse(json.dumps(message), | |
content_type="application/json", | |
status=status.HTTP_401_UNAUTHORIZED) | |
class OAuth2ProtectedGraph(OAuth2ProtectedResourceMixin, GraphQLView): | |
@classmethod | |
def as_view(cls, *args, **kwargs): | |
view = super(OAuth2ProtectedGraph, cls).as_view(*args, **kwargs) | |
return view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment