Django Rest Framework和Angularjs身份验证

时间:2018-09-16 08:08:46

标签: angularjs django rest django-rest-framework

我对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',
)

2 个答案:

答案 0 :(得分:0)

您使用以下身份验证:

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.BasicAuthentication',
    'rest_framework.authentication.SessionAuthentication',
),

令牌:您必须从服务器获取令牌,并在每个请求中添加一个标头,例如此示例(来自docs):

Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

会话:您必须从前端登录,并在登录后获取cookie集。检查客户端,查看sessionidcsrf是否是cookie中的注册键值。 (使用适用于Firefox和chrome的插件Awesome Cookie Manager)。 csrf是所有危险HTTP方法(POST,PUT,DELETE ...)必需的令牌,必须将其设置为来自服务器的cookie。

基本:基本身份验证仅用于测试,我什至不在设置中使用它。

所有详细信息都在这里:http://www.django-rest-framework.org/api-guide/authentication/

错误地设置了CORS。

尝试以下方法:

CORS_ORIGIN_ALLOW_ALL = False

# A list of regexes that match origin regex list of origin hostnames
# that are authorized to make cross-site HTTP requests
CORS_ORIGIN_REGEX_WHITELIST = (
    r'^(https?://)?(localhost|127\.0\.0\.1|0\.0\.0\.0)(:\d{4})?$',
)

# Check here: 
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
CORS_ALLOW_CREDENTIALS = True

答案 1 :(得分:0)

我通过在前端添加这个来解决了这个问题:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);