postman 如何解决“细节”:基于类的APIView Django REST框架出现“未提供身份验证凭据”错误?

8fsztsew  于 2023-03-02  发布在  Postman
关注(0)|答案(3)|浏览(233)

我正在使用DjangoREST框架,并按照本教程在管理员用户通过身份验证时检索所有用户。
Class-based APIView of Django REST Framework
我正在使用Postman进行测试,并尝试检索系统中注册的所有用户的列表。
首先,我尝试使用Postman中的"User Login with Token" API创建必要的令牌,如下所示:

我复制了"token"键的值,并将其粘贴为Postman中"Get All Users" API的"Headers"部分中"Authorization"键的值,如下所示。这是一个GET请求,我得到的响应是错误"detail": "Authentication credentials were not provided."

必要的代码片段如下所示:

    • 查看次数. py**
class UserAccountListView(APIView):
"""
    List of All Users in the System / Application
    * Requires Token Authentication.
    * Only Admin Users are able to access this view.
"""
authentication_classes = (TokenAuthentication, )
permission_classes = (IsAdminUser, )

def get(self, request, format=None):
    """
        Returns a List of All Users
    """
    full_names = [user.full_name for user in UsersAccount.objects.all()]
    return Response(full_names)
    • 设置. py**
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.IsAdminUser',
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=1),
    "ROTATE_REFRESH_TOKENS": False,
    "BLACKLIST_AFTER_ROTATION": False,
    "UPDATE_LAST_LOGIN": True,

    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY,
    "VERIFYING_KEY": None,
    "AUDIENCE": None,
    "ISSUER": None,

    "AUTH_HEADER_TYPES": ("Bearer", ),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",

    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken", ),
    "TOKEN_TYPE_CLAIM": "token_type",

    "JTI_CLAIM": "jti",

    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),
}
    • 网址. py**
urlpatterns = [
    path('', UsersAccountAPIOverview.as_view()),
    path("all", UserAccountListView.as_view()),
    path("register", UsersAccountRegistrationView.as_view()),
    path("token", UserAccountTokenObtainPairView.as_view()),
    path("token/refresh", TokenRefreshView.as_view()),
    path("token/verify", TokenVerifyView.as_view()),
]

期待您的善意支持和帮助。如果您需要进一步的信息,我会提供给您。
谢谢你。

t98cgbkg

t98cgbkg1#

在www.example.com中views.py删除以下行:

authentication_classes = (TokenAuthentication, )

这是因为在您的settings.py文件中,第一行:

'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework_simplejwt.authentication.JWTAuthentication',
    ...
],

提到了JWT身份验证而不是令牌身份验证

bbuxkriu

bbuxkriu2#

必须在 Postman 中添加 Postman :
"授权":"持票人[代币]"

ybzsozfc

ybzsozfc3#

我正在使用cookiecuter + django,这是真棒,以及踢你的屁股。jaja但由于我对继续我的项目感兴趣,我只是在www.example.com评论这行base.py(在您的情况下,它将在settings.py)

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
    # "rest_framework.authentication.SessionAuthentication",
    # "rest_framework.authentication.TokenAuthentication",
),
# "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",

}
这对我来说很有效,只是为了测试我的端点,我知道这不是最好的方法,但很有效,我稍后会用更好的方法更新我的答案。

相关问题