8

为 Django 编写的两个 JWT 包都给我带来了文档质量差的问题,所以我尝试了 DRF-auth_token 包。这是我遵循的一个很好的例子,Django Rest Framework Token Authentication。理论上你应该可以去

localhost:8000/api-token-auth/

网址.py:

from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework.authtoken import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api/', include('api.urls', namespace='api')),
    url(r'^orders/', include('orders.urls', namespace='orders')),
    url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'),

]

为用户获取令牌不起作用,所以我自己重写了它以使其工作:

@api_view(['POST'])
def customer_login(request):
    """
    Try to login a customer (food orderer)
    """
    data = request.data

    try:
        username = data['username']
        password = data['password']
    except:
        return Response(status=status.HTTP_400_BAD_REQUEST)

    try:
        user = User.objects.get(username=username, password=password)
    except:
        return Response(status=status.HTTP_401_UNAUTHORIZED)

    try:
        user_token = user.auth_token.key
    except:
        user_token = Token.objects.create(user=user)

    data = {'token': user_token}
    return Response(data=data, status=status.HTTP_200_OK)

我的版本有效:

http://localhost:8000/api/login/customer-login/
{"username": "thisguy@example.com", "password": "wombat"}
-->
{
  "token": "292192b101153b7ced74dd52deb6b3df22ef2c74"
}

DRF auth_token 不起作用:

http://localhost:8000/api-token-auth/
{"username": "thisguy@example.com", "password": "wombat"}
-->
{
  "non_field_errors": [
    "Unable to log in with provided credentials."
  ]
}

设置.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # third party:
    'django_extensions',
    'rest_framework',
    'rest_framework.authtoken',



REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    )
}

似乎设置正确。我数据库中的每个用户都有一个令牌。每个用户都is_authenticatedis_active数据库中。超级用户可以获得他们的令牌:

localhost:8000/api-token-auth/
{"username": "mysuperuser", "password": "superuserpassword"}
-->
{
  "token": "9297ff1f44dbc6caea67bea534f6f7590d2161b0"
}

出于某种原因,只有超级用户才能获得令牌:

localhost:8000/api-token-auth/
{"username": "regularguy", "password": "password"}
-->
{
  "non_field_errors": [
    "Unable to log in with provided credentials."
  ]
}

为什么我的用户无法登录并获取他们的令牌?谢谢

4

9 回答 9

21
于 2019-11-13T05:18:35.380 回答
6

我继续从drf token auth docs执行此操作,并且没有遇到超级用户、staffuser 或普通用户的任何问题。

还可以尝试按照官方文档的步骤而不是那个答案,看看是否可以解决问题 - 可能发生了一些变化。

以下是我采取的一般步骤:

  • 安装 django, drf
  • 将“rest_framework”和“rest_framework.authtoken”放入 INSTALLED_APPS
  • 在我的 rest_framework 设置中添加“TokenAuthentication”
  • 运行迁移
  • 为用户创建令牌(我刚刚在 urls.py 中做了这个)
  • 为令牌创建 url
  • POST http://localhost:8000/token/ {"username": "...", "password": "..."}

如果您将代码公开在任何地方,我很乐意进一步查看并查看我的发现。

于 2016-10-17T02:53:57.753 回答
5

也许加密是罪魁祸首。我面临同样的问题。我比较了存储在mysql中的信息superuser和一个普通用户(姑且称之为user1)。我发现了不同之处。的密码superuser已加密,但user1的密码未加密。所以我把user1's 的密码改成了superuser's 的密码,然后我把名字和密码user1到 jwt api 上,我得到了正确的答案

现在我找到了一个答案,虽然它可能不是最好的,但它应该可以工作。我刚刚覆盖了“ModelSerializer”中的“create”方法。step1:将“ModelSerializer”中的“create”方法复制到您自己的序列化程序文件中 step2:将句子“instance = ModelClass._default_manager.create(**validated_data)”更改为“instance = ModelClass._default_manager.create_user(**validated_data) ”。在此处输入图像描述 第 3步:成功了![在此处输入图像描述] 4 [ 在此处输入图像描述] 5

于 2019-03-15T13:18:51.460 回答
4
  1. 检查用户名和密码
  2. 表 users.is_active = 1 中的字段
于 2018-08-08T15:57:10.780 回答
1

对我来说,我使用密码创建了用户1234

在用户管理面板中,我看到了以下消息

密码:密码格式无效或散列算法未知。

在使用 django 密码限制(至少 8 个字符和其他一些字符)更新密码后,我在 resposne 中获得了令牌。

于 2020-06-07T08:44:09.710 回答
1

我希望这对那些使用TokenAuthentication(不是 JWT)django-allauthdj-rest-auth得到相同错误的人有所帮助。

另一个类似问题的答案对我有用。

我只需要在以下位置添加这些身份验证后端settings.py

AUTHENTICATION_BACKENDS = (
   "django.contrib.auth.backends.ModelBackend",
   "allauth.account.auth_backends.AuthenticationBackend"
)
于 2021-06-22T09:23:09.250 回答
0

可能有多种原因,但恕我直言,澄清这一点的最简单方法是激活设置文件中的日志(使用“级别”:“调试”)并通过“api-token-auth”查看生成的 SQL 选择查询

例如,我的个人在阅读此请求时跳出来:

SELECT 
    profileapp_customuser.id, profileapp_customuser.password,
    profileapp_customuser.last_login, profileapp_customuser.is_superuser,
    [...]
    profileapp_customuser.email FROM profileapp_customuser
WHERE
    **profileapp_customuser.email = 'username_test3**' LIMIT 21;

事实上,我的自定义模型无法运行,因为我的用户唯一 ID 不再是用户名而是电子邮件。

于 2021-03-02T13:49:13.500 回答
0

在我的情况下,我使用usernameandpassword进行身份验证。但是由于项目中的以下自定义代码已经存在由其他人开发的 djangoauthenticte 方法,因此期望email value对密钥不利username

class User(AbstractUser):
    .....
    USERNAME_FIELD = 'email'

所以我提供了反对username让它发挥作用。

请参阅屏幕截图以供参考

使用用户名值

在此处输入图像描述

使用电子邮件值

在此处输入图像描述

注意:这是因为 Django 根据字段查找过滤了用户名值,根据提到USERNAME_FIELD的值请参阅下面的代码参考

https://github.com/django/django/blob/61d5e57353bb811df7b5457a1856baee31299429/django/contrib/auth/backends.py#L42

user = UserModel._default_manager.get_by_natural_key(username)

于 2021-03-29T08:44:50.037 回答
0

密码不正确

>>> nameko.Platform.Auth({'username': 'user', 'password': 'pass'})
[{'token': 'eefd5c0f747e121b9cb9986290f66b3c1089669d'}, 2
于 2020-11-17T19:39:44.570 回答