文章目录
Django rest framwork jwt
http://jpadilla.github.io/django-rest-framework-jwt/
1. 安装
注意:切换到自己项目的 Python 环境中进行安装
$ pip3 install djangorestframework-jwt
2. 使用
2.1 全局设置使用
在 settings.py
中,添加JSONWebTokenAuthentication
到 Django REST 框架的DEFAULT_AUTHENTICATION_CLASSES
。
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
在 urls.py
中添加以下URL 路由, 这样可以启用通过 POST 请求来获得用户令牌的功能,发送 POST 请求时需要提供用户的用户名和密码。
2.2 视图设置使用
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class UsersSeriaView(APIView):
authentication_classes = [JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
配置 URL
from rest_framework_jwt.views import obtain_jwt_token
#...
urlpatterns = [
'',
# ...
path(r'api-token-auth/', obtain_jwt_token),
]
设置 Tocken 有效时间和认证 token 信息的前缀
在 settings.py
文件中设置
import datetime
JWT_AUTH = {
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
postman 工具
创建postman请求
获取 token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTY5MTQ3MzgzLCJlbWFpbCI6ImFkbWluQHNoYXJrLmNvbSJ9.v5t9lr2zEnI0nlTfTl3FRdHMmiEMBO1Mwp5zQV6i5kY
使用 JWT token
curl 工具
如果您使用用户名admin和密码password123创建用户,则可以通过在终端中执行以下操作来轻松测试端点是否正常运行。
$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/
使用 JSON 格式提交
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/
接下来就可以使用 Token 获取相应数据了
$ curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/