使用django权限.带有令牌身份验证的IsAuthenticatedOrReadOnly



我有这个Django API视图,我想允许授权和未授权的用户访问它,我已经将Django token-authentication设置为默认的身份验证类,但是,每当我试图以未经身份验证的用户访问该视图时,我都会得到错误未授权:这很奇怪,因为我正在视图中发出get请求我的代码在这里

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
print(request.headers)
src = request.GET.get('q')

我的rest框架设置是

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}

有办法解决这个问题吗?感谢的帮助

我试图重现您的错误,但失败了。这是我的配置:

settings.py

INSTALLED_APPS = [
...
'rest_framework',
'rest_framework.authtoken'
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}

urls.py

urlpatterns = [
path('search/', api.all_search, name="search")
]

api.py

from rest_framework import permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
print(request.headers)
src = request.GET.get('q')
return Response()

test.py

from rest_framework import status
from rest_framework.test import APILiveServerTestCase
from rest_framework.reverse import reverse
class TestTokenAuthorization(APILiveServerTestCase):
def test_can_search_without_token(self):
url = reverse('search', kwargs={})
response = self.client.get(url, {}, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)

这是测试的结果:

Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'Cookie': '', 'Content-Type': 'application/octet-stream'}
Destroying test database for alias 'default'...

我正在使用djangorestframework==3.10.3python3.7

正如您所看到的,我没有对请求进行身份验证(没有传递令牌(,并且按照权限的预期打印了标头。

也许您的问题是由代码中的其他内容引起的。试着在你的问题中包含更多的细节。

顺便说一下,您的all_Search函数缺少return Response()

好吧,我刚决定尝试一下,至少目前是这样。不知何故,我认为DEFAULT_AUTHENTICATION_CLASSES是本例中的问题,事实上确实如此,所以我不得不删除

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
]
}
#opt to use
#authentication_classes = [TokenAuthentication, SessionAuthentication]
#in my views that requires authentications

在我的设置中,这还不是全部,但现在我可以访问该视图,无论是否授权:(是否具有auth令牌(。但默认情况下,这并没有得到经过身份验证的用户所以我做了这个

根据给定的令牌查看以获得用户

from django.contrib.auth.models import AnonymousUser
from rest_framework.authtoken.models import Token
def get_user(token):
try:
token = Token.objects.select_related('user').get(key=token)
return token.user
except:
return AnonymousUser

并在我的视图中获取用户,如果标头中存在令牌

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticatedOrReadOnly])
def all_Search(request):
auth = request.headers.get('Authorization').split(' ')[1]
key = request.headers.get('Authorization').split(' ')[0]
if key == 'Token' and auth != 'null': #used null coz my frontend sends null if key is not available
user = get_user(auth)
print(user)

相关内容

最新更新