不要求OPTIONS请求进行身份验证 [英] Do not require authentication for OPTIONS requests
问题描述
我的settings.py
My settings.py
REST_FRAMEWORK = {
'UNICODE_JSON': True,
'NON_FIELD_ERRORS_KEY': '__all__',
'DEFAULT_AUTHENTICATION_CLASSES': (
# TODO(dmu) HIGH: Support OAuth or alike authentication
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'ALLOWED_VERSIONS': ['v1'],
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning',
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
'TEST_REQUEST_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
当我这样做我会得到身份验证错误:
When I do this I get authentication error:
curl -X OPTIONS http://127.0.0.1:8000/api/passenger/v1/order/ | python -m json.tool
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 58 0 58 0 0 469 0 --:--:-- --:--:-- --:--:-- 475
{
"detail": "Authentication credentials were not provided."
}
我希望我的服务器响应模式描述,而不需要身份验证。同时我希望它像往常一样要求GET,POST,PUT,PATCH和DELETE请求进行身份验证。
I'd like my server respond with "schema" description and not required authentication. At the same time I want it to require authentication for GET, POST, PUT, PATCH and DELETE requests as usual.
如何实现?
我的解决方案
谢谢Alasdair的意见。我个人使用此解决方案:
Thank you, Alasdair, for the idea. I personally used this solution:
from rest_framework.permissions import DjangoObjectPermissions
OPTIONS_METHOD = 'OPTIONS'
class DjangoObjectPermissionsOrOptions(DjangoObjectPermissions):
def has_permission(self, request, view):
if request.method == OPTIONS_METHOD:
return True
else:
return super(DjangoObjectPermissions, self).has_permission(request, view)
推荐答案
Django休息框架附带权限类 IsAuthenticatedOrReadOnly
,允许经过身份验证的用户执行任何请求,未经授权的用户可以进行GET,HEAD或OPTIONS请求。
Django rest framework comes with a permissions class IsAuthenticatedOrReadOnly
, which allows authenticated users to perform any request, and unauthorised users to make GET, HEAD or OPTIONS requests.
您的用例非常相似,因此您可以尝试以下(未测试):
Your use case is pretty similar, so you could try the following (untested):
class IsAuthenticatedOrOptions(BasePermission):
"""
The request is authenticated as a user, or an OPTIONS request.
"""
def has_permission(self, request, view):
return (
request.method == 'OPTIONS' or
request.user and
request.user.is_authenticated()
)
'DEFAULT_PERMISSION_CLASSES': (
'path.to.IsAuthenticatedOrOptions',
),
这篇关于不要求OPTIONS请求进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!