本文不讲解具体原理,只编写操作步骤
**
1.安装json web token
**
通过pip 安装
pip install djangorestframework-jwt -i https://mirrors.aliyun.com/pypi/simple/ ( 此处用的是阿里的pip源 -下载速度较快)
2.在已经创建好的Django项目中的setting文件中进行配置
具体如图

REST_FRAMEWORK = {
# 设置所有接口都需要被验证
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
}
3.设置views视图层
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = [SessionAuthentication, JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance.
'auth': unicode(request.auth), # None
}
return Response(content)
4.设置url路由 设置在项目的主url中
from rest_framework_jwt.views import obtain_jwt_token
url(r'^api-token-auth/', obtain_jwt_token),

5.启动项目
python manage.py runserver
6.通过jmeter 调用 这个接口
1.打开jemter 填入url 端口号
2.在参数中添加 username 和password 并输入对应的 用户名(此处的用户名填写能够进入 django admin后台的那个账号)

3.点击启动,查看结果数,此时token已经给返回

7.携带后端返回的token进行登录
未完待续
本文详细介绍了如何在Django项目中使用JSON Web Tokens (JWT)进行用户认证,包括安装Django REST framework JWT、配置settings、设置视图层、URL路由及通过jmeter测试等关键步骤。
1791

被折叠的 条评论
为什么被折叠?



