目录:
- SessionAuthentication验证
- django 自带登录源码分析
- postman测试结果
一、SessionAuthentication验证
我们之前讨论了BasicAuthentication、TokenAuthentication 验证。我们现在来讨论一下 Session 验证。废话不多说我们来看下,怎么使用session验证的。当然我们都是在 局部环境下测试的,如果想要全局下测试,需要在Settings.py中 需要配置全局验证。这个在TokenAuthentication验证的博客中有。我就不多说了。
1.1、视图
说明:导入session验证,并且使用。再次声明,这边是局部配置,只对当前视图有效。
.... from rest_framework.authentication import BasicAuthentication, TokenAuthentication, SessionAuthentication #导入SessionAuthentication验证 from rest_framework.permissions import IsAuthenticated # Create your views here. class CartView(APIView): # 基于什么登录认证的 authentication_classes = [BasicAuthentication, TokenAuthentication, SessionAuthentication] #支持session验证,三者任何一种验证都可以,这边我们主要用 Session验证 # 只有登录才能访问 permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): .... return JsonResponse(ctx)
哈哈,就这么简单
二、django 自带登录源码分析
小伙伴们有没有发现一个问题,就是我们在访问 admin 后台登录,输入用户名密码的时候,后台会自动生成 session。好啊,废话不多少说了,直接看下源码怎么写的:
2.1、导入登录模块
from django.contrib.auth import login
2.2、查看登录源码
说明:Ctrl + login 走你 看看到底有啥:
def login(request, user, backend=None): session_auth_hash = '' if user is None: user = request.user if hasattr(user, 'get_session_auth_hash'): session_auth_hash = user.get_session_auth_hash() #登录的时候生成了一个session_id if SESSION_KEY in request.session: if _get_user_session_key(request) != user.pk or ( session_auth_hash and not constant_time_compare(request.session.get(HASH_SESSION_KEY, ''), session_auth_hash)): # To avoid reusing another user's session, create a new, empty # session if the existing session corresponds to a different # authenticated user. request.session.flush() else: request.session.cycle_key() ....未完待续
2.3、登录admin后台
说明:访问 http://127.0.0.1:8000/admin。当然这个用户是你用 python manage.py createsuperuser 创建出来的。
登录成功后,我们来看下数据库django_session:
三、postman测试结果
3.1、浏览器测试
3.2、postman测试结果
说明:postman测试的时候就要手动的把 cookie(上面浏览器生成的cookie) 输入到请求 头当中。
注意:这边有一个要强调一个 只有 post、put、delete等方法才会收到 crf_token影响,get方法是不受影响的。