Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To authenticate tokens sent from the frontend in DJANGO using AUTH0, you can follow these steps:

  1. Set up an AUTH0 account and create a new application. Choose either the Single Page Application or Regular Web Application.

  2. 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.

  3. Install the AUTH0 Python library in your DJANGO project using pip.

  4. In your DJANGO settings.py file, add the following settings:

AUTH0_DOMAIN = 'YOUR_AUTH0_DOMAIN'
AUTH0_API_IDENTIFIER = 'YOUR_API_IDENTIFIER'
  1. Create a 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
  1. In your DJANGO 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),
]
  1. Finally, in your frontend application, you can use the 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.