Django Rest Framework和Angularjs认证

问题描述 投票:0回答:2

我有一个Authentification抛出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)

我认为Class视图是正确的。并且在发送用户凭证抛出请求后它工作正常。我的问题是我有另一个类视图,需要用户进行身份验证。所以当我使用postman它工作正常我访问request.user并返回登录用户。但是使用代码我得到的参数必须是字符串,类似字节的对象或数字,而不是'AnonymousUser'。

我是否需要在HTTP请求中添加标头?因为我注意到邮递员使用cookies

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',
)
angularjs django rest django-rest-framework
2个回答
0
投票

您使用这些身份验证:

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

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

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

0
投票

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

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
© www.soinside.com 2019 - 2024. All rights reserved.