【问题标题】:Django rest framework JWT not returning web tokenDjango rest框架JWT不返回Web令牌
【发布时间】:2016-06-27 20:25:23
【问题描述】:

我已遵循Django REST framework JWT 中指定的所有说明。但是当我使用我的自定义用户模型登录时,它不起作用。

settings.py

...

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

自定义用户管理器:

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, **kwargs):
        if not email:
            raise ValueError('Users must have a valid email address.')

        user = self.model(
            email=self.normalize_email(email), full_name=kwargs.get('full_name')
        )

        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, email, password, **kwargs):
        user = self.create_user(email, password, **kwargs)
        user.is_admin = True
        user.save()

        return user

这是我用于登录的views.py:

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body)

        email = data.get('email', None)
        password = data.get('password', None)

        account = authenticate(email=email, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)
                serialized = UserSerializer(account)
                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

【问题讨论】:

  • 向您显示的错误是什么?有什么不好的地方?
  • 没有错误。一切都像未配置一样工作。
  • 你检查你安装的应用了吗?
  • 是的,它也适用于默认登录 DRF 登录 API (api-token-auth)。
  • 默认情况下,令牌应在向POST /api-token-auth/ 的请求中返回。您如何尝试获取令牌?

标签: django django-rest-framework


【解决方案1】:

如果你使用 django rest 框架 authtoken

你可以这样做

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

【讨论】:

    【解决方案2】:

    JWT(JSON Web 令牌)身份验证的重点是使用特定算法生成的token

    为了让您的LoginView 正常工作,您需要:

    1. 验证用户身份
    2. 使用rest_framework_jwt.utils.jwt_encode_handler方法生成JWT令牌
    3. 将生成的令牌添加到响应负载中

    您可以查看 DRF-JWT 模块的源代码以了解这是如何完成的,但除非您想大幅修改响应负载(例如,通过包含与用户模型),我建议您使用隐式身份验证并使用现有模块 API 调整行为。

    【讨论】:

    • 按照您的要求进行了更改。我正在尝试登录我的自定义登录视图,但收到错误 {"detail":"Authentication credentials were not provided."} 即使默认登录 API 工作正常。
    【解决方案3】:

    检查已安装的应用:

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'django_extensions',
        'rest_framework',
    )
    

    【讨论】:

    • 是的,它确实有一个条目“rest_framework”。此外,我的 DRF 流程正在运行。它只是网络令牌没有被返回。
    猜你喜欢
    • 2018-11-19
    • 2018-07-24
    • 2017-01-25
    • 2015-10-19
    • 2019-10-31
    • 2018-12-15
    • 2013-01-28
    • 2023-03-29
    • 2020-07-16
    相关资源
    最近更新 更多