[英]Django rest framework Anonymous user is always Authenticated
I'm trying to authenticate my web API method using django rest framework isauthenticated permission and TokenAuthentication The API method:我正在尝试使用 django rest framework isauthenticated 权限和 TokenAuthentication API 方法来验证我的 Web API 方法:
@api_view(['Post'])
@permission_classes((IsAuthenticated,))
def listofgroups(request):
try:
logout(request)
data = request.data
page_size = data.get('pagesize')
page_number = data.get('pagenumber')
group_qs = Group.objects.all()
paginator = Paginator(group_qs, int(page_size))
group_list = paginator.page(int(page_number))
#group_list = tools.paginate_query_set(group_qs, 1, 3)
#list = group_list[0]['model']
groups = [get_group_dto(g) for g in group_list]
sorted_groups = sorted(groups, key=lambda k: k['user_count'], reverse = True)
group_list_dto = {
"grps": sorted_groups,
"success":1,
"fail":0
}
return Response(group_list_dto)
except Exception as e:
#.error("Error %s"(e), exc_info = 1)
return Response({"success" : 0, "error": str(e)})
Basically i should always set Authorization in the header like :基本上我应该总是在标题中设置授权,如:
"Authorization":"Token a26171d30745cc94bcd6ac42d9bc94e1d3992948"
"授权":"令牌a26171d30745cc94bcd6ac42d9bc94e1d3992948"
this token is based on rest_framework.authtoken此令牌基于 rest_framework.authtoken
The Error is that I can get the data with response 200 without even setting the Token in the header because its returning anonymous user which is authenticated from the back end in django.错误是我可以使用响应 200 获取数据,甚至无需在标头中设置令牌,因为它返回的匿名用户是从 django 后端进行身份验证的。
How can I prevent anonymous users from being authenticated and return 403 response error for them using django rest framework
如何使用 django rest 框架阻止匿名用户进行身份验证并为他们返回 403 响应错误
I appreciate any help我感谢任何帮助
There are actually many classes defined in django rest framework for validation purposes.实际上,django rest 框架中定义了许多用于验证目的的类。 What I guess in your case is that you will need the following set of decorators:
我猜你的情况是你需要以下一组装饰器:
@api_view(['POST'])
@authentication_classes((TokenAuthentication,))
@permission_classes((IsAuthenticated,))
Considering you have set the header properly it wont be a problem with the above code.考虑到您已经正确设置了标题,上面的代码不会有问题。
you can this do,你可以这样做
to stay safe and always ask the user for a token, and you don't need to call permission_classes, it will automatically be isAuthenticated为了安全起见,始终要求用户提供令牌,并且您不需要调用permission_classes,它会自动进行isAuthenticated
REST_FRAMEWORK = {
DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.