python - 检查用户是否使用 django TokenAuthentication 进行身份验证

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

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

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

@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>

这基本上就是我为其他人所做的 View 集 (这不是 View 集)我有 - 它有效。

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

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

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

谢谢!

已解决

正如“ABDUL NIYAS P M”所建议的,我使用了 APIView

基本上,我只是添加了 @api_view(['GET']) View 的装饰器。
@csrf_exempt
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def foo(request):
    if request.method == 'GET':
        ...

最佳答案

一种更简单的方法是检查用户 session 是否存在。
当 DRF 创建 token 时,它也会创建 session cookie。

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

关于python - 检查用户是否使用 django TokenAuthentication 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47184231/

相关文章:

python - 为 Flask-CORS 指定域

python - 如何使用 Docker 创建 Python 可执行文件

python - 在 GCP Cloud-Build 上构建 Django 项目

django - 嵌套序列化程序中的当前用户

django - 如何为组和管理员设置权限

python - 如何复制数据并替换一列中的值?

python - 我如何将 DecimalField 转换为在 Python Django 中 float ?

python - 如何将 "lang"属性添加到 python-markdown 中的 <pre> 标记?

python - Django-Haystack with Solr 包含搜索

django - 验证 Swagger API 文档 (drf-yasg)