1 | initial version |
To authenticate tokens sent from the frontend in DJANGO using AUTH0, you can follow these steps:
Set up an AUTH0 account and create a new application. Choose either the Single Page Application or Regular Web Application.
Configure your application by adding your DJANGO server's domain under Allowed Callback URLs, Allowed Web Origins, and Allowed Logout URLs. Then, under the Advanced tab, add a new rule that sets audience = YOUR_API_IDENTIFIER
.
Install the AUTH0 Python library in your DJANGO project using pip.
In your DJANGO settings.py
file, add the following settings:
AUTH0_DOMAIN = 'YOUR_AUTH0_DOMAIN'
AUTH0_API_IDENTIFIER = 'YOUR_API_IDENTIFIER'
auth0backend.py
file in your DJANGO project and add the following code:from auth0.v3.authentication import GetToken
class Auth0Backend(object):
def authenticate(self, request):
auth_header = request.META.get('HTTP_AUTHORIZATION')
token = auth_header.split()[1]
try:
gt = GetToken('YOUR_AUTH0_DOMAIN')
decoded = gt.login('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET', 'urn:ietf:params:oauth:grant-type:jwt-bearer', audience='YOUR_API_IDENTIFIER', assertion=token)
return decoded
except Exception:
return None
def get_user(self, user_id):
return None
urls.py
file, add the following code:from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token
from .auth0backend import Auth0Backend
backend = Auth0Backend()
urlpatterns = [
url(r'^auth/login/$', obtain_jwt_token),
]
auth0-js
library to retrieve the user's access token and include it in the request headers.With these steps, your DJANGO server will be able to authenticate tokens sent from the frontend using AUTH0.