1
votes

I have the following setup:

  • Apache Webserver running a Django Frontend Webpage
  • Application Server running a Django REST Framework

I now have to integrate the the Django Frontend into a 3rd party project which is written in java and angular. The authentication is completely handled by this 3rd party.

Users login over LDAP and create a JWT token.

Is it possible to simply receive the token in Django and authenticate the User after successfully decoding the token? And how would this work with the @login_required decorator when I have protected functions?

Is there some sort of project where I can orient on, or do I have to write all myself?

1

1 Answers

0
votes

I use a built-in User model to store usernames. This enables me to login the user when authentication is successful and then use Django functionalities such as @login_requested as you'd normally use them.

Below is a sample code (without the code for REST authentication).

from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views.decorators.cache import never_cache

@never_cache
def user_login(request):
    ''' User login '''

    if request.user.is_authenticated:
        return HttpResponseRedirect(reverse('main:index'))

    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # Your code for authentication here
        # authenticate =  .... 

        if authenticate:
            # Get user // create one if it doesn't exist yet
            user, created = User.objects.get_or_create(username=username)
            # Login user - @login_required decorator can be used after user has been logged in
            login(request, user)
            next = request.POST.get('next', '/') if request.POST.get('next') else '/'
            return HttpResponseRedirect(next)
        else:
            messages.warning(request, 'Authentication failed', extra_tags=forgot_password)
            return HttpResponseRedirect(reverse('main:login'))
    else:
        return render(request, 'main/login.html', {})