django-rest-framework框架_第四篇_认证Authentication
认证Authentication
什么是身份认证
身份验证是将传入请求与一组标识凭据(例如请求来自的用户或与其签名的令牌)关联的机制.
视图的最开始处运行身份验证
在权限和限制检查发生之前,以及在允许继续执行任何其他代码之前,始终在视图的最开始处运行身份验证.
身份验证方案总是定义为类的列表
REST框架尝试对列表中的每个类进行身份验证,并将成功身份验证的第一个类的返回值赋值给request.user request.auth. 如果没有类身份验证,则request.user将设置为django.contrib.auth.models.anonymousUser的实例,request.auth将设置为none.
验证的执行过程
①.、在APIView中重写 dispatch方法,方法最后有一段描述:? ?
# Ensure that the incoming request is permitted 确保传入进来的
request是被允许的 self.perform_authentication(request) #执行验证
self.check_permissions(request) #检查全选
self.check_throttles(request) #检查阀门
这个方法只有这么一句话 获取user 其实这是Request类的一个user方法
def user(self): 走到 def _authenticate(self):
方法 在这个方法中有 for authenticator in self.authenticators:
user_auth_tuple = authenticator.authenticate(self)
表示遍历我们设置的authentication_classes属性中的所有验证类列表,每个验证类都去执行类中的authenticate()方法.
BasicAuthentication(了解)
BasicAuthentication
此身份验证方案使用HTTP基本身份验证,根据用户的用户名和密码进行签名.基本身份验证通常只适用于测试.
如果验证成功,则basicauthentication提供以下凭据.
① request.user将是Django用户实例
② request.auth将为无
并带有适当的www-authenticate头.例如:www authenticate:basic realm="api"
SessionAuthentication(了解)
如果验证成功,sessionauthentication将提供以下凭据.
① request.user将是Django用户实例.
② request.auth将为无.
postman
Postman 是一个很强大的 API调试、Http请求的工具. 有chrome插件版, 有本地软件版,这里是有本地安装包安装.
认证类配置
局部配置 在具体的view类中写
authentication_classes = [BearerToken]
全局配置
在setting中配置
REST_FRAMEWORK = {
) }
TokenAuthentication
如果验证成功,TokenAuthentication 将提供以下凭据.
② request.auth将是rest_framework.authtoken.models.Token实例.
Token验证使用
使用步骤
① 把rest_framework.authtoken添加到INSTALLED_APPS中
② 把TokenAuthentication类写入authenticate_classes属性中
③ migration迁移数据库 因为会生成Token相关的数据表
④ 配置token的路由: from rest_framework.authtoken import views
如果验证通过,TokenAuthentication 提供以下凭证:request.user Django自带的User模型实例
① request.auth rest_framework中的Token模型实例
例如:WWW-Authenticate: Token
Token总结:
①.、令牌的好处:避免在使用中不断的输入账号和密码,比较安全
自定义Token(重点)
继承BaseAuthentication
重写authenticate
返回return 两个值
以上就是能诗百科小编为大家整理的django-rest-framework框架_第四篇_认证Authentication相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!
