AngellusMortis / django_microsoft_auth

Simple app to enable Microsoft Account, Office 365 and Xbox Live authentcation as a Django authentcation backend.
MIT License
137 stars 84 forks source link

Roles to Django Groups? #465

Open mke21 opened 2 years ago

mke21 commented 2 years ago

Hi,

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

AngellusMortis commented 2 years ago

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

mke21 commented 2 years ago

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.

lisabutti commented 2 years ago

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

mke21 commented 2 years ago

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.

lisabutti commented 2 years ago

Thank you @mke21 ! this worked for me