Django REST framework 登录验证JWT实践

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请求

在这里插入图片描述

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KPcWbzdi-1599822683426)(evernotecid://BBD579E0-7127-4377-8E81-47BEA574FA91/appyinxiangcom/25594833/ENResource/p711)]
在这里插入图片描述

获取 token

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IonrVJLZ-1599822683459)(evernotecid://BBD579E0-7127-4377-8E81-47BEA574FA91/appyinxiangcom/25594833/ENResource/p709)]

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/

猜你喜欢

转载自blog.csdn.net/qq_22648091/article/details/108540196
今日推荐