【问题标题】:Check if user is authenticated with django TokenAuthentication检查用户是否使用 django TokenAuthentication 进行身份验证
【发布时间】:2018-04-21 09:46:26
【问题描述】:

我正在尝试使用 DRF 开发一个使用 TokenAuthentication 的 REST API。这将在 android 应用程序中使用。

我能够对用户进行身份验证并检索它的令牌。我现在遇到的问题是以下观点:

@csrf_exempt
def foo(request):
    if request.method == 'GET':
        if request.user.is_authenticated():
            ...
            do stuff
            ...
            return HttpResponse(data, "application/json")
        else:
            return HttpResponse(status=401)

基本上用户应该通过身份验证才能接收数据,否则,他将收到 401 响应。

我正在使用标头中的以下参数向正确的 URL 发出 GET 请求:

content-type : application/json
authorization : Token <user token>

这基本上是我为其他 Viewsets(这不是 Viewset)所做的 - 而且它有效。

在这种情况下,它总是发送带有 401 代码的 HTTP 响应(用户未通过身份验证)。

我无法确定问题是否出在我传递的标头值上,或者这不是检查用户是否已通过身份验证的正确方法。

编辑:如果我这样做:“print request.user”我得到 AnonymousUser

谢谢!

已解决

按照“ABDUL NIYAS P M”的建议,我使用了 APIView

基本上,我只是将 @api_view(['GET']) 装饰器添加到视图中。

@csrf_exempt
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def foo(request):
    if request.method == 'GET':
        ...

【问题讨论】:

  • Abdu,我错过了你之前所说的 api_view 装饰器。谢谢!

标签: python django django-rest-framework django-views


【解决方案1】:

更简单的方法是检查用户会话是否存在。

当 DRF 创建令牌时,它也会创建会话 cookie。

return HttpResponse(json.dumps({"is_authenticated": True if request.session.get('_auth_user_id', 0) else False}),
                            content_type='application/json')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多