Django中的认证与权限 源码剖析

网友投稿 700 2022-11-21

Django中的认证与权限 源码剖析

Django中的认证与权限 源码剖析

rest_framework/request.py中部分认证和权限代码

def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. """ for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self.user, self.auth = user_auth_tuple return self._not_authenticated() def _not_authenticated(self): """ Set authenticator, user & authtoken representing an unauthenticated request. Defaults are None, AnonymousUser & None. """ self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() else: self.user = None

认证后将user存储到了request中,为了权限使用时候可以进行判断(红色)

class UserLoginPermission(BasePermission):     def has_permission(self, request, view):

return isinstance(request.user,User)

实例

authentication.py

from django.core.cache import cachefrom rest_framework.authentication import BaseAuthenticationclass TokenAuthentication(BaseAuthentication): def authenticate(self, request): token = request.query_params.get("token") user = cache.get(token) if user: return user ,token

permissions.py

from rest_framework.permissions import BasePermissionfrom App.models import Userclass UserLoginPermission(BasePermission): def has_permission(self, request, view): return isinstance(request.user,User) def has_object_permission(self, request, view, obj): if obj.b_author.id == request.user.id: return True

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Django REST framework【学习内容】
下一篇:jpa多条件查询重写Specification的toPredicate方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~