djangodjango-microsoft-authentication

Mapping roles in AzureAD to Django groups


Okay, I can now do SSO in Django via AzureAD by using django-microsoft-auth. But I would like to manage the groups there as well. For that we configured to pass roles in the token. But how do I map those to Django groups? I don't seem to find any example for that.


Solution

  • Found it. For anyone with the same question, you'll have to use the 'MICROSOFT_AUTH_AUTHENTICATE_HOOK' setting.

    I made a module in my 'app' called aad.py:

    import jwt
    def add_to_group(user, token):
        from django.contrib.auth.models import Group
        id_token = token['id_token']
        token_data = jwt.decode(id_token, options={"verify_signature": False})
        roles = token_data.get('roles', [])
        user.groups.clear()
        for r in roles:
            current_group, created = Group.objects.get_or_create(name=r)
            current_group.user_set.add(user)
    

    in the settings I added the following setting:

    MICROSOFT_AUTH_AUTHENTICATE_HOOK = "myApp.aad.add_to_group"
    

    Of course things could be neater, but it works for now.