[英]Not able to authenticate using the django rest framework (request.user = AnonymousUser)
I am trying to configure authentication for the incoming request but I am not able to understand the required steps to achieve it. 我正在尝试为传入请求配置身份验证,但是我无法理解实现此请求的必需步骤。
I have followed the steps provided in the documentation 我已按照文档中提供的步骤进行操作
First, I edited the setting.py
for the auth settings: 首先,我编辑了auth设置的setting.py
:
INSTALLED_APPS = [
...,
'rest_framework',
'rest_framework.authtoken',
...,
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
}
In the view.py
: 在view.py
:
@csrf_exempt
def uuid_details(request, uuid):
if request.method == 'GET':
print "user: " + str(request.user) # user: AnonymousUser
So when I invoke above rest API, in the above line I am getting output as AnonymousUser
. 因此,当我调用上述rest API时,在上一行中,我得到的输出为AnonymousUser
。 As per my understanding, I should receive the authenticated User
object. 根据我的理解,我应该收到经过身份验证的User
对象。
I am able to retrieve the token and passing it to the rest API. 我能够检索令牌并将其传递给其余的API。
>>> Token.objects.get(user=user)
<Token: 95119884347cf000caab9d2596b9a18a9103f1db>
So, I am not able to understand how the authentication works in Django rest framework. 因此,我无法理解身份验证在Django rest框架中的工作方式。
It looks like you have a regular Django view, so none of the rest framework authentication code will run. 看起来您具有常规的Django视图,因此其余框架身份验证代码均不会运行。
def uuid_details(request, uuid):
You could use the api_view
decorator to turn this into a rest framework view. 您可以使用api_view
装饰器将其转换为rest框架视图。
from rest_framework.response import Response
from rest_framework.decorators import api_view
@api_view(['GET'])
def uuid_details(request, uuid):
return Response({"message": "user: " + str(request.user)}
Two things: 两件事情:
It should work once those two points are fixed. 一旦确定了这两点,它就应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.