注意:切换到自己项目的 Python 环境中进行安装
djangorestframework-jwt 已经停止跟新,不再支持,Django官方推荐
文档 https://django-rest-framework-simplejwt.readthedocs.io/en/latest/
Github: https://github.com/jazzband/djangorestframework-simplejwt
pip3 install djangorestframework-simplejwt
在 settings.py
中,添加JSONWebTokenAuthentication
到 Django REST 框架的DEFAULT_AUTHENTICATION_CLASSES
。
REST_FRAMEWORK = {
...
'DEFAULT_AUTHENTICATION_CLASSES': (
...
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
...
}
# 设置 Tocken 有效期
import datatime
SIMPLE_JWT = {
# token有效时长(返回的 access 有效时长)
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=7),
# token刷新的有效时间(返回的 refresh 有效时长)
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=5),
}
url 设置
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
...
# token 认证
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
# token 刷新
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
你也可以对某个视图使用
from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication
from rest_framework.permissions import IsAuthenticated
class UsersSeriaView(APIView):
authentication_classes = [JWTTokenUserAuthentication]
permission_classes = [IsAuthenticated]
url 不变
如果您使用用户名admin和密码password123创建用户,则可以通过在终端中执行以下操作来轻松测试端点是否正常运行。
使用 JSON 格式提交
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8080/api/token/
发回值:
{"refresh":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwNDI3NzM3NCwiaWF0IjoxNzAzODQ1Mzc0LCJqdGkiOiJiM2M0ODY0MmMxZmI0YTNjODgyMDljZTZmYzc2ZTNiNSIsInVzZXJfaWQiOjF9.rdUyFQdpCXLkbv0caZUQhir8-9Y-7rRgCNwsHShkts0",
"access":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA0NDUwMTc0LCJpYXQiOjE3MDM4NDUzNzQsImp0aSI6IjUwNjA4MjQ4N2FmNzQyZjE4ZWFlZDA0N2E1NzIyZTk4IiwidXNlcl9pZCI6MX0.3wcijHHWAJtyJX8gpCIaFmU_5JID9GAJBes2mv6eCvg"}
接下来就可以使用 Token 获取相应数据了
curl \
-H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA0NDUwMTc0LCJpYXQiOjE3MDM4NDUzNzQsImp0aSI6IjUwNjA4MjQ4N2FmNzQyZjE4ZWFlZDA0N2E1NzIyZTk4IiwidXNlcl9pZCI6MX0.3wcijHHWAJtyJX8gpCIaFmU_5JID9GAJBes2mv6eCvg" http://localhost:8080/v1/users