【发布时间】:2019-02-20 11:04:24
【问题描述】:
我遇到了 Authentification throw Django REST API 的问题。前端与后端是分开的。前端在服务器端口 8008 上运行,后端在 Django 8000 上运行。问题是我在 setting.py 中添加了 CORS 设置,而我的问题是 api 工作正常,除非我想访问需要身份验证的数据。这是认证类视图:
class LoginView(APIView):
permission_classes = (AllowAny,)
def get(self, request, format=None):
print('executed scc!!!')
content = {
'status': 'request was permitted'
}
return Response(content)
def post(self, request):
print('Loging in !!!')
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data["user"]
django_login(request, user)
print(request.user)
token, created = Token.objects.get_or_create(user=user)
return Response({"token": token.key}, status=200)
我认为类视图是正确的。在发送用户凭据抛出发布请求后它工作正常。我的问题是我有另一个需要对用户进行身份验证的类视图。所以当我使用邮递员时它工作正常我访问 request.user 并返回登录用户。但是我得到了代码 参数必须是字符串、类似字节的对象或数字,而不是“AnonymousUser”。
我需要在我的 HTTP 请求中添加标头吗?因为我注意到邮递员使用 cookie
INSTALLED_APPS = [
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
}
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8008',
)
CORS_ORIGIN_REGEX_WHITELIST = (
'localhost:8008',
)
【问题讨论】:
-
您能在设置中分享您的 REST 配置吗?
-
我添加了设置
标签: angularjs django rest django-rest-framework