Authorization and Permissions in Django
Keith Bussell @keithb
LA Django 9/6/16
Authentication
Verification of who you are based on credentials such as username and password
Authorization
Verification of what you can access or do based on permissions
Authorization
Use for anything you don't want seen or done by everyone
Small Blog Example
Step 1: Django admin with built-in permissions
Superuser vs Staff user with Permissions
Step 2: Adding a custom permission
Groups are your friends
Groups
- As soon as you have more than a couple of permissions, you will want to use groups
- Document your groups! They can get complicated
- Prefer to keep groups definitions in one place
| View | Add | Change | Delete | Publish | |
|---|---|---|---|---|---|
| Visitor | Published | ✘ | ✘ | ✘ | ✘ |
| Author | ✔︎ | ✔︎ | Own | Own | ✘ |
| Publisher | ✔︎ | ✘ | ✘ | ✘ | ✔︎ |
| is_staff | ✔︎ | N/A | N/A | N/A | N/A |
Blog Post Permissions
Group definitions
- Define them in code to keep them consistent across environments
- Data migrations don't work well for permissions
- Spread out across multiple migrations
- Need to get timing to work with creation of content types and permissions
- Connect to the post_migrate signal
Step 3: Object-level Permissions
Outgrowing the Django Admin
Handling object permissions
Django’s permission framework has a foundation for object permissions, though there is no implementation for it in the core. That means that checking for object permissions will always return False or an empty list (depending on the check performed). An authentication backend will receive the keyword parameters obj and user_obj for each object related authorization method and can return the object level permission as appropriate.
https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#handling-object-permissions
Step 4: A new auth backend
And moving out of the Django Admin
Prefer using an existing permissions library
django-permissions
- Write logic in code
- More code
- Potentially faster for larger datasets
django-guardian
- More similar to Django's permissions, but pass an object to every assign_perm call
- Less code
- One db row for every object/user combination
Step 5: Adding visitor permissions
Appendix: DRF's permission handling
Differences from Django
- Permissions are classes in DRF
- For interoperability, check out DjangoModelPermissions and DjangoObjectPermissions
Thanks!
https://slides.com/keithbussell/django-perms
https://github.com/kbussell/django-permissions-talk
Keith Bussell @keithb
Authorization and Permissions in Django
By Keith Bussell
Authorization and Permissions in Django
- 696