认证authentication
什么是身份认证
身份验证是将传入请求与一组标识凭据(例如请求来自的用户或与其签名的令牌)关联的机制。
视图的最开始处运行身份验证
在权限和限制检查发生之前,以及在允许继续执行任何其他代码之前,始终在视图的最开始处运行身份验证。
身份验证方案总是定义为类的列表
rest框架尝试对列表中的每个类进行身份验证,并将成功身份验证的第一个类的返回值赋值给request.user request.auth。 如果没有类身份验证,则request.user将设置为django.contrib.auth.models.anonymoususer的实例,request.auth将设置为none。
验证的执行过程
1、在apiview中重写 dispatch方法,方法最后有一段描述:
# ensure that the incoming request is permitted 确保传入进来的
request是被允许的 self.perform_authentication(request) #执行验证
self.check_permissions(request) #检查全选
self.check_throttles(request) #检查阀门
2、def perform_authentication(self, request): request.user
这个方法只有这么一句话 获取user 其实这是request类的一个user方法
3、@property
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将为无
③ http 401未经身份验证,
并带有适当的www-authenticate头。例如:www authenticate:basic realm=“api”
sessionauthentication(了解)
此身份验证方案使用django的默认会话后端进行身份验证。会话身份验证适用于与网站在同一会话上下文中运行的ajax客户端。
如果验证成功,sessionauthentication将提供以下凭据。
① request.user将是django用户实例。
② request.auth将为无。
③ 拒绝权限的未经身份验证的响应将导致http 403禁止响应。
postman
postman 是一个很强大的 api调试、http请求的工具。 有chrome插件版, 有本地软件版,这里是有本地安装包安装。
认证类配置
局部配置 在具体的view类中写
authentication_classes = [bearertoken]
全局配置
在setting中配置
rest_framework = {
'default_authentication_classes': (
'rest_framework.authentication.basicauthentication',
'rest_framework.authentication.sessionauthentication',
) }
tokenauthentication
此身份验证方案使用简单的基于令牌http身份验证。令牌身份验证适用于client-server分离的情况,如本机桌面和移动客户端。
如果验证成功,tokenauthentication 将提供以下凭据。
① request.user将是django用户实例。
② request.auth将是rest_framework.authtoken.models.token实例。
③ 拒绝权限的未经身份验证的响应将导致http 401 unauthorized。
token验证使用
使用步骤
① 把rest_framework.authtoken添加到installed_apps中
② 把tokenauthentication类写入authenticate_classes属性中
③ migration迁移数据库 因为会生成token相关的数据表
④ 配置token的路由: from rest_framework.authtoken import views
path("api-token/", views.obtain_auth_token)
token验证使用
获取token key令牌 令牌要包含authorization http header authorization: token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
如果验证通过,tokenauthentication 提供以下凭证:request.user django自带的user模型实例
① request.auth rest_framework中的token模型实例
② 验证失败,则返回http 401 unauthorized 并携带www-authenticate 头信息
例如:www-authenticate: token
token总结:
1、令牌的好处:避免在使用中不断的输入账号和密码,比较安全
2、如果要测试带token的接口,首先要进行登录,登录成功会有个token信息,向api接口发送请求的时候必须带上这个token,
故需要做2次请求(1,登录,拿到token 2,正式对接口进行测试)
自定义token(重点)
继承baseauthentication
重写authenticate
返回return 两个值
续更 ...待续...
如对本文有疑问, 点击进行留言回复!!
PC-Arduino Serial communication using python
网友评论