我正在使用 REST API 和 Django Rest Framework 做一个项目。目前,我的发布请求中存在一个问题,即我的某些端点返回 HTTP 401 Unauthorized,尽管所有其他获取或更新对象都返回正确的响应。我正在使用 -> djangorestframework-simplejwt==5.2.2.
设置.py
INSTALLED_APPS = [
# ...
'rest_framework_simplejwt.token_blacklist',
# ...
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=50),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
"JSON_ENCODER": None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}
主网址.py
schema_view = get_schema_view(
openapi.Info(
title="Blog Backend API's",
default_version="v1",
description="This is the documentation for the backend API",
terms_of_service="http://mywebsite.com/policies/",
contact=openapi.Contact(email="[email protected]"),
license=openapi.License(name="BDSM License"),
),
public=True,
permission_classes=(permissions.AllowAny, )
)
urlpatterns = [
path('admin/', admin.site.urls),
path("api/v1/", include("api.urls")),
path("", schema_view.with_ui('swagger', cache_timeout=0), name="schema-swagger-ui"),
]
views.py
class PostCommentApiView(APIView):
@swagger_auto_schema(
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'post_id': openapi.Schema(type=openapi.TYPE_INTEGER),
'name': openapi.Schema(type=openapi.TYPE_STRING),
'email': openapi.Schema(type=openapi.TYPE_STRING),
'comment': openapi.Schema(type=openapi.TYPE_STRING),
},
),
)
def post(self, request):
post_id = request.data["post_id"]
name = request.data["name"]
email = request.data["email"]
comment = request.data["comment"]
post = api_models.Post.objects.get(id=post_id)
api_models.Comment.objects.create(
post=post,
name=name,
email=email,
comment=comment,
)
api_models.Notification.objects.create(
user=post.user,
post=post,
type="Comment"
)
return Response({"message": "Comment Sent"}, status=status.HTTP_201_CREATED)
api/urls.py
urlpatterns = [
path("post/comment-post/", api_views.PostCommentApiView.as_view()),
]
我收到此回复
{
"detail": "Authentication credentials were not provided."
}
在我的终端中,我收到“未经授权:/api/v1/post/comment-post/”。我该如何解决这个帖子请求问题。我想做一个大项目,但我被所有的帖子请求困住了。
如果你查看settings.py
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
默认权限类指定为 IsAuthenticated,默认身份验证类指定为 JWTAauthentication。
这就是为什么只有经过身份验证和身份验证的用户才会被允许处理所有请求。
你遇到的401错误也是设置了JWTAuthentication作为默认的认证类,这是客户端发出请求而没有设置与认证相关的header时出现的错误。
Authorization: Bearer {access_token}
如果你的PostCommentAPIVIew是需要认证授权的类,客户端必须以“Bearer {access_token}”的形式在请求头中传递,作为Authorization key的值。
但是,如果 PostCommentAPIView 是允许所有用户的逻辑,则应删除 settings.py DefaultPermission、DefaultAuthentication 或应覆盖该值。
class PostCommentApiView(APIView):
authentication_classes = []
permission_classes = []
@swagger_auto_schema(
...
)
def post(self, request):
...