rest framwork之登录验证源码解析

最近开始用restframework框架,刚一拿到项目完全是无数脸懵逼,所以接下来自己学习来对框架进行一些讲解,希望能够给初用框架的朋友带来一些帮助,错误和不足之处欢迎大家指出!
登录认证流程
1、请求进来先找APIView的dispatch
2、对request进行了封装

Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),#[BasicAuthentication()对象,]
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )
    	#self.get_authenticators()#返回[BasicAuthentication()对象,]
    	#authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES#可以自己重写 自定义认证类

3、self.initial(request, *args, **kwargs)认证
4、self.perform_authentication()
def perform_authentication(self, request):
5、 request.user
6、request类里找user
def user():
7、self._authenticate()
循环认证类的所有对象
源码:

def _authenticate(self):
	        """
	        Attempt to authenticate the request using each authentication instance
	        in turn.
	        """
	        #循环遍历认证的所有对象
	        for authenticator in self.authenticators:
	            try:
	                #执行认证类的所有authenticate方法
	                #1、如果authenticate方法抛出异常,self._not_authenticated()执行,认证失败
	                #2、如果没有抛出异常,
	                	#1、有返回值,必须是有两个元素的元组,(request.user,request.auth)函数结束,认证通过
	                	#2、没有返回值,返回NONE,继续执行authentication_classes里面的下一个认证,如果都没有返回值,则执行self._not_authenticated(),self.user=AnonymousUser,self.auth=None   ()
	                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()

8、执行自己写的authenticate方法
9、执行get/post/put/patch/…
#自定义的类放在views里是局部认证
2、全局使用认证
在settings里面写

REST_FRAMEWORK = {
		"DEFAULT_AUTHENTICATION_CLASSES":[自己定义得认证类]
		#自己定义的认证类不要放在views里面,可以自己建一个文件夹放里面
		#自己定义的认证类要写绝对路径
		#'UNAUTHENTICATED_USER': lanbda:"匿名用户",
		'UNAUTHENTICATED_USER': None,#匿名用户,request.user=None
    	'UNAUTHENTICATED_TOKEN': None,#匿名用户,request.user=None
	}

全局都需要认证,当某一个类里面不需要认证时,比如第一次登陆,在这个类里面加上下面一句话就OK了
authentication_classes = []

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Django REST framework (DRF) 可以使用 Token 认证Session 认证和 JSON Web Token (JWT) 认证等方式进行登录验证。 其中,Token 认证Session 认证是最基本的认证方式,它们都使用了 Django 自带的用户认证系统,适合于简单的应用场景。Token 认证是通过在请求头中添加 Token 来进行认证,而 Session 认证则是在 Cookie 中保存 Session ID 来进行认证。 JWT 认证则是一种更加灵活和安全的认证方式,它使用了基于 JSON 的 Token,可以完全脱离 Django 自带的用户认证系统,支持跨域访问和分布式系统。JWT 认证需要在 DRF 中添加相应的中间件和配置,同时也需要在前端实现 Token 的生成和保存。 在 DRF 中使用 Token 认证Session 认证,只需要在 settings.py 文件中添加相应的认证方式,如: ```python REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], } ``` 在视图函数中使用 `@authentication_classes` 装饰器来指定认证方式,如: ```python from rest_framework.decorators import authentication_classes from rest_framework.authentication import TokenAuthentication, SessionAuthentication @authentication_classes([TokenAuthentication, SessionAuthentication]) @api_view(['GET']) def my_view(request): # ... ``` JWT 认证需要使用第三方库 `djangorestframework-jwt`,并在 settings.py 文件中添加相应的配置,如: ```python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_jwt', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } JWT_AUTH = { 'JWT_SECRET_KEY': 'your_secret_key', 'JWT_ALGORITHM': 'HS256', 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7), 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30), } ``` 在视图函数中使用 `@jwt_authetication_classes` 装饰器来指定 JWT 认证方式,如: ```python from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework.decorators import jwt_authetication_classes @jwt_authetication_classes([JSONWebTokenAuthentication]) @api_view(['GET']) def my_view(request): # ... ``` 以上是 DRF 中常见的登录验证方式,可以根据具体的应用场景选择合适的认证方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值