我已按照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)
答案 0 :(得分:0)
检查已安装的应用:
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'rest_framework',
)
答案 1 :(得分:0)
JWT(JSON Web令牌)身份验证的重点是使用特定算法生成的WideState
。
要使token
正常工作,您需要:
LoginView
方法您可以查看DRF-JWT模块的源代码以了解如何完成此操作,但除非您希望大幅修改响应有效负载(例如,通过包含与之无关的模型的序列化表示形式)用户模型),我建议您使用隐式身份验证并使用现有模块API调整行为。
答案 2 :(得分:0)
如果你使用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',
),
}