django_microsoft_auth icon indicating copy to clipboard operation
django_microsoft_auth copied to clipboard

Roles to Django Groups?

Open mke21 opened this issue 2 years ago • 5 comments

Hi,

Is it possible to map the roles in AzureAD to django groups? I can't seem to find any example of that.

mke21 avatar Dec 14 '21 11:12 mke21

Not implemented. Make a PR to add if you want it.

AngellusMortis avatar Dec 14 '21 13:12 AngellusMortis

Okay, clear.

BTW, I just found out that I could do this by using the 'MICROSOFT_AUTH_AUTHENTICATION_HOOK' setting. So maybe just a simple update to the documentation would suffice.

mke21 avatar Dec 14 '21 13:12 mke21

How did you use the MICROSOFT_AUTH_AUTHENTICATION_HOOK setting for map the roles into django groups?

lisabutti avatar May 09 '22 09:05 lisabutti

First I installed de PyJWT package.

Then I added a module with a function in one of the apps, say the module is `my_app.msauth:

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)

And I added the following to the django settings.py:

MICROSOFT_AUTH_AUTHENTICATE_HOOK = "my_app.msauth.add_to_group"

Of course, use your own app and module name.

mke21 avatar May 09 '22 14:05 mke21

Thank you @mke21 ! this worked for me

lisabutti avatar May 20 '22 10:05 lisabutti