Force set request.user in code

I’m using Azure AD to login to my django app.

I have the Django app such that there is a list of users under the application_users which is synced with the AD users manually.

But when someone logins as john@acme.com in Azure AD how do I set the request.user to, say, id 57 after matching against the email address ?

@ms_identity_web.login_required
def profile(request):

    claims = request.identity_context_data._id_token_claims
    print(claims['preferred_username'])
    print(request.identity_context_data.username)
    print("current user = ", request.user)
    return render(request, 'profile.html', { 'msid': claims['preferred_username'], 'django_username': request.user })

Do you want to get request.user id within the views then you can access it as request.user.id
Or do you want to set request.user to certain object like {“id”: 1, “name”: “test”}

I want request.user to be set to a particular user object.

From here you can see request.user comes from Authentication middleware Request and response objects | Django documentation | Django.
So in order to store custom object in request.user you have to create custom middleware.

This seems to work on my local :

@ms_identity_web.login_required
def profile(request):

    claims = request.identity_context_data._id_token_claims

    try:
        application_user = User.objects.get(email=claims['preferred_username'])
        request.user = application_user
    except User.DoesNotExist:
        print("not able to find from users table")

    if request.user.is_authenticated:
        print("user is authenticated")
    else:
        print("not authenticated")

    return render(request, 'profile.html', { 'msid': claims['preferred_username'], 'django_username': request.user })

Now how do I get this code to run for every route ?

You create it as middleware as previously suggested. That’s the purpose of middleware - it runs on every request.

Thanks got it - I realized I had to put the AZ checking code after response = self.get_response(request)

        # Code to run before the view is called
        response = self.get_response(request)
        # Code to run after the view is called and before the response is returned