Skip to content

Instantly share code, notes, and snippets.

@aeros281
Last active May 19, 2022 02:05
Show Gist options
  • Save aeros281/b3046381e931db64de679f33d6cf6567 to your computer and use it in GitHub Desktop.
Save aeros281/b3046381e931db64de679f33d6cf6567 to your computer and use it in GitHub Desktop.
Django Auth0
import jwt
from functools import wraps
# Create your views here.
def get_token_auth_header(request):
"""Obtains the access token from the Authorization Header
"""
auth = request.META.get("HTTP_AUTHORIZATION", None)
parts = auth.split()
token = parts[1]
return token
def requires_scope(required_scope):
"""Determines if the required scope is present in the access token
Args:
required_scope (str): The scope required to access the resource
"""
def require_scope(f):
@wraps(f)
def decorated(*args, **kwargs):
token = get_token_auth_header(args[0])
decoded = jwt.decode(token, verify=False)
if decoded.get("scope"):
token_scopes = decoded["scope"].split()
for token_scope in token_scopes:
if token_scope == required_scope:
return f(*args, **kwargs)
response = JsonResponse({'message': 'You don\'t have access to this resource'})
response.status_code = 403
return response
return decorated
return require_scope
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment