所以,我的 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 请求库。
谢谢你的时间,
您不api/token
使用标头发出请求,而是执行 POST 请求并在正文中传递凭据。使用 Requests 2.4.2,你可以这样做:
requests.post(
"http://localhost:8000/api/token/",
json={"username": "davidattenborough", "password": "boatymcboatface"}
)
如果您的令牌已过期,您将收到状态代码为 的响应401
。您调用刷新端点。如果您的刷新令牌已过期,也会出现401
. 然后您必须使用您的凭据重新进行身份验证。使用请求,您可以通过以下方式获取状态.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"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句