【问题标题】:Django Rest Framework and Angularjs authentificationDjango Rest 框架和 Angularjs 身份验证
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您使用这些身份验证:

    '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
    

    【讨论】:

    • 感谢您的回复,我会照您说的做的。我只有一个令我困惑的问题是 csrf 令牌与用户令牌相同。因为登录后我确实从后端获取了用户令牌。以及如何使用 angularjs 设置 cookie?谢谢
    • csrf token 用于Session认证,你应该决定使用什么:Session还是Token? cookie 由服务器设置,客户端在每次调用时发送 cookie。使用 cookie 时不应该做任何事情(在 Session 身份验证中)
    • 我忘记了 CSRF 令牌的一件事。如果您使用会话,请记住在执行危险请求时在标头中使用 CSRF 令牌。在这里查看:docs.djangoproject.com/en/2.1/ref/csrf/…
    • 还是不行!我仍然收到此错误:TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser'
    猜你喜欢
    • 2013-06-29
    • 2017-09-26
    • 2017-11-02
    • 2019-03-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多