Search code examples
djangoazureauthenticationazure-active-directorydecorator

Django : How can we custom login_required decorator?


I want to write a decorator like the login_required decorator of Django to check the Azure AD authentication and the Django authentication at the same time. If one of the two is not true, it redirects to the login page.

For the authentication, I used the tutorial (https://learn.microsoft.com/en-us/graph/tutorials/python). I do not how to deal with groups and permissions since I use Azure AD authentication. So I take the username and surname from the token that comes from the Azure Authentication and with this two infos, I create an user in the User Django models. I know it is not the best idea, but I can start to play with groups and permissions.

The django authentication is automatic without that the user create it. It is done in the callback function.

def callback(request):
  
    # Make the token request
    result = get_token_from_code(request)

    #Get the user's profile
    user = get_user(result['access_token'])

    # Store user
    store_user(request, user)

    # Get user info
    # user attribute like displayName,surname,mail etc. are defined by the 
    # institute incase you are using single-tenant. You can get these 
    # attribute by exploring Microsoft graph-explorer.

    username = user['displayName']
    password = user['surname']
    email = user['mail']

    try:
        # if use already exist
        user = User.objects.get(username=username)

    except User.DoesNotExist:
        # if user does not exist then create a new user
        user = User.objects.create_user(username,email,password)
        user.save()

    user = authenticate(username=username,password=password)

    if user is not None:
        login(request,user)
        messages.success(request,"Success: You were successfully logged in.")
        return redirect('home')
    return redirect('home')

If I want to check if the user is authenticated by Azure AD. From the tutorial, I should do something like that :

if request.session.get('user').get('is_authenticated') :

But I do not know how to combine with the django authentication to check both. Anyone can help me

Thanks


Solution

  • Here is my solution :

    from django.shortcuts import redirect
    
    
    def authenticated_user(view_func) :
        def wrapper_func(request, *args, **kwargs):
    
            if request.user.is_authenticated and request.session.get('user').get('is_authenticated') :
        
                return view_func(request, *args, **kwargs)
    
            else : 
    
                return redirect('login')
    
        return wrapper_func