Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Authentication and Permissions with Django REST...
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Ordoquy Xavier - Linovia
October 16, 2016
Programming
190
0
Share
Authentication and Permissions with Django REST framework
An overview of the authentication and permissions management with Django REST framework.
Ordoquy Xavier - Linovia
October 16, 2016
More Decks by Ordoquy Xavier - Linovia
See All by Ordoquy Xavier - Linovia
SQLAlchemy - un ami qui vous veut du bien
xordoquy
0
18
pycon.fr 2018 - Django REST framework workshop
xordoquy
0
350
mauvaises bonnes idées pour REST
xordoquy
1
400
Buildbot 0.9
xordoquy
0
110
Performances Django REST framework - DjangoCong 2016
xordoquy
0
130
Présentation de l'architecture REST - meetup Django Paris
xordoquy
0
110
Django REST framework workshop @Djangocon Europe 2015
xordoquy
0
130
Django REST framework - DjangoConG 2015
xordoquy
3
150
Django REST framework workshop - DjangoCong 2015
xordoquy
1
130
Other Decks in Programming
See All in Programming
正しくソフトウェアを作る、前提を疑うための認知の視点 / doubt-premise
minodriven
6
2.9k
oxlintはeslint/typescript-eslintを置き換えられるのか
shomafujita
2
300
Spec-Driven Development with AI-Agents: From High-Level Requirements to Working Software
antonarhipov
2
410
TSKaigi2026-静的解析への投資がAI時代のコード品質を支える ── カスタムESLintルールの設計と運用
hayatokudou
7
1.3k
Inspired By RubyKaigi (EN)
atzzcokek
0
480
Make SRE Operations Easier with Azure SRE Agent
kkamegawa
0
2.6k
OCRを使ってゲームのアイテムをデータ化する
kishikawakatsumi
0
120
代数的データ型って何が嬉しいの? #frontend_phpcon_do
kajitack
7
2.9k
Modding RubyKaigi for Myself
yui_knk
0
840
ReactとSvelteのその先、Ripple-TS / Beyond React and Svelte: Ripple-TS
ssssota
3
1.9k
Signal Forms: Beyond the Basics @ngBaguette 2026 in Paris
manfredsteyer
PRO
0
200
Lessons from Spec-Driven Development
simas
PRO
0
110
Featured
See All Featured
Leo the Paperboy
mayatellez
7
1.8k
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
A Guide to Academic Writing Using Generative AI - A Workshop
ks91
PRO
1
310
Google's AI Overviews - The New Search
badams
0
1k
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
70
39k
Digital Ethics as a Driver of Design Innovation
axbom
PRO
1
300
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
4k
ピンチをチャンスに:未来をつくるプロダクトロードマップ #pmconf2020
aki_iinuma
128
55k
What the history of the web can teach us about the future of AI
inesmontani
PRO
1
600
How to build a perfect <img>
jonoalderson
1
5.5k
GraphQLの誤解/rethinking-graphql
sonatard
75
12k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.5k
Transcript
Django REST framework Authentification Permissions Xavier Ordoquy
Mainteneur Django REST framework Freelance irc: linovia twitter: linovia_net
Django
DJANGO @login_required() def someview(request): ... ?
DJANGO MIDDLEWARE = [ "django...SessionMiddleware", "django...AuthenticationMiddleware", ] @login_required() def someview(request):
... !
Auth =/= Perm
Django REST framework
CLASSE VUE class ExampleView(APIView): authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated]
FONCTION @api_view(['GET']) @authentication_classes([SessionAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): return Response({})
SETTINGS REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', ) }
vue >> settings
Pourquoi ne pas réutiliser Django ?
DJANGO MIDDLEWARE = [ "django...SessionMiddleware", "django...AuthenticationMiddleware", ] @login_required() def someview(request):
...
Problème: authentifications différentes
Problème: trop lié à l’utilisateur
Problème: Middleware pour tout le site
SITE vs API { "count": 2, "next": null, "previous": null,
"results": [ { "email": "
[email protected]
", "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" }, { "email": "
[email protected]
", "groups": [ ], "url": "http://127.0.0.1:8000/users/2/", "username": "tom" } ] }
Inclus: Basic
Inclus: Session
Inclus: Token
3RD PARTIES • Django OAuth2 Consumer • JSON Web Token
Authentication • Hawk HTTP Authentication • HTTP Signature Authentication • django-rest-framework-social-oauth2 • Digest Authentication • Djoser • django-rest-auth • django-rest-knox
401 / 403
403 Forbidden The request was successfully authenticated, but permission was
denied.
401 Unauthorized The request was not successfully authenticated, and the
highest priority authentication class does use "WWW-Authenticate" headers
403 Forbidden The request was not successfully authenticated, and the
highest priority authentication class does not use "WWW-Authenticate" headers. > SessionAuthentication <
pas de header pas de 401 401 Unauthorized
CSRF
CSRF @csrf_exempt
CSRF Géré par SessionAuth…
PERMISSIONS
• AllowAny • IsAuthenticated • IsAdminUser • IsAuthenticatedOrReadOnly • DjangoModelPermissions
• DjangoModelPermissionsOrAnonReadOnly • DjangoObjectPermissions INCLUS
DjangoModel Permissions Permissions par Model de django.contrib.auth
PERSONALISATION GET OPTIONS HEAD POST…………………….. PUT………………….. PATCH………………. DELETE……………….. <app label>.add_<model
name> <app label>.change_<model name> <app label>.change_<model name> <app label>.delete_<model name> perms_map
DjangoObject Permissions Permissions par objet de django.contrib.auth (django-guardian ou autre)
PERMISSIONS PAR OBJET SUR LISTE ?
class CustomObjectPermissions(DjangoObjectPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], 'HEAD':
['%(app_label)s.view_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer filter_backends = [filters.DjangoObjectPermissionsFilter] permission_classes = [CustomObjectPermissions]
WTF ?!? mes permissions sont appelées 6 x ?
COUPABLE
Pas de permissions sur mon get_object !!
SURCHAGE view.get_object def get_object(self): queryset = self.filter_queryset(self.get_queryset()) filter_kwargs = ###
obj = get_object_or_404(queryset, **filter_kwargs) self.check_object_permissions(self.request, obj) return obj
CACHE GLOBAL (MIDDLEWARE) Pas de gestion de permissions
Permissions complexes ?
Et si j’avais besoin de lire la requête ?
from rest_framework.exceptions import PermissionDenied raise PermissionDenied( 'Some permission failed’ )
Ecrire son auth
from django.contrib.auth.models import User from rest_framework import authentication from rest_framework
import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None)
Ecrire ses perms
from rest_framework import permissions class BlacklistPermission(permissions.BasePermission): def has_permission(self, request, view):
ip_addr = request.META['REMOTE_ADDR'] blacklisted = Blacklist.objects.filter( ip_addr=ip_addr).exists() return not blacklisted
class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in
permissions.SAFE_METHODS: return True return obj.owner == request.user
One more thing
Pérennité http://www.django-rest- framework.org/topics/funding/
As a direct result of a successful Mozilla grant application,
I will be leaving my current role at DabApps, and attempting to secure a sustainable business model for REST framework development. I need your help in order to make this work. -Tom Christie
MERCI @linovia_net