【问题标题】:How to actually use DRF + JWT Authentication with Python Requests如何在 Python 请求中实际使用 DRF + JWT 身份验证
【发布时间】:2020-01-27 22:02:12
【问题描述】:

所以,我的 Django“时间管理”应用程序有一个休息 API。我正在为我的 API 使用 JWT(JSON Web 令牌)授权。我已经配置了所有设置和视图,但我并没有清楚地掌握它实际工作的概念。我的应用程序有一个客户端,它将使用这些身份验证令牌来增加出勤率。

这是我项目的url.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView


urlpatterns = [
    path('', admin.site.urls),
    path('time/', include('timemanagement.urls')),
    path('api-auth', include("rest_framework.urls")),
    path('api/token/', TokenObtainPairView.as_view()),
    path('api/token/refresh/', TokenRefreshView.as_view()),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

问题 1 - 基本上,当我的应用程序第一次启动时,我希望它做什么? 我假设我需要首先使用我的用户名和密码作为标题向'myserver.com/api/token/' 发出请求,但我不知道如何使用 Python Requests 库执行此操作。

问题 2 - 假设我的令牌已过期。我的客户端应用程序如何知道这一点? (通过使用该令牌发送请求,那么我猜我会收到错误?)如果是这样,我如何处理此错误以获取新令牌?如果该令牌也过期了怎么办,因为'api/token/refresh/' 这次只给出一个令牌,没有刷新令牌。

另外,每次加载我的应用程序时,我是否必须使用我的管理员凭据从“api/token”请求一个新令牌,或者一个应用程序是否只有一个令牌会一遍又一遍地刷新。 我没有使用 POSTMAN,我将使用 Python 请求库。

感谢您的宝贵时间,

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:
    1. 您不使用标头发出请求api/token,而是发出 POST 请求并在正文中传递凭据。使用 Requests 2.4.2,您可以这样做:

      requests.post(
          "http://localhost:8000/api/token/",
          json={"username": "davidattenborough", "password": "boatymcboatface"}
      )
      
    2. 如果您的令牌已过期,您将收到状态码为401 的响应。您调用刷新端点。如果您的刷新令牌已过期,那也会给出一个401。然后,您必须使用您的凭据重新进行身份验证。使用 Requests,您可以通过.status_code 获取状态:

      response = requests.get(...)
      response.status_code
      

      或者,您可以从令牌中读取过期时间并主动刷新/重新进行身份验证。客户端可以读取 JWT 令牌,但不能验证内容。这足以从“exp”字段中读取到期时间。您可以为此使用库 PyJWT。像这样的:

      response = requests.post(
          "http://localhost:8000/api/token/",
          json={"username": "davidattenborough", "password": "boatymcboatface"}
      )
      tokens = response.json()
      access_expiration = jwt.decode(token["access"], verify=False)["exp"]
      refresh_expiration = jwt.decode(token["refresh"], verify=False)["exp"]
      

    【讨论】:

    • 我们开始了。一个美丽而详细的答案。谢谢楼主,
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2020-12-19
    • 2023-03-31
    • 2021-07-03
    • 2021-04-10
    • 2022-01-20
    • 2017-11-02
    • 2019-08-07
    相关资源
    最近更新 更多