[英]django custom authentication backend with custom middleware (both username,password and token absed auth)
[英]Cannot log in to token endpoint with username/password: drf token auth and custom user model, Django
我有一個基本的 Django 應用程序,使用 Django rest 框架,一個自定義用戶 Z20F35E630DAF,5349DBFA4C3F68 繼承自默認的基本令牌8 身份驗證。 我可以通過運行python3./manage.py drf_create_token {USERNAME/EMAIL}
為任何用戶生成令牌,並使用它驗證相關請求。 但是,當我嘗試訪問我的令牌端點(在本例中http://127.0.0.1:8000/api/token/
或已部署應用程序的等效項)時,我得到
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
我的請求正文(應用程序/json)如下:
{
"username": "test@test.com",
"password": "test"
}
我已確保用戶處於活動狀態; 密碼正確; 並且用戶名與 email 相同。
我的自定義用戶 class:
class Customer(AbstractUser):
first_name = models.CharField(max_length=240)
last_name = models.CharField(max_length=240)
email = models.EmailField(unique=True)
phone_number = PhoneNumberField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
is_active=models.BooleanField(default=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["password", "phone_number", "first_name", "last_name", "username"]
def __str__(self):
return f"{self.first_name} {self.last_name}"
相關網址:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/users/', include('customer.urls')),
path('api/token/', obtain_auth_token, name="auth_token"),
]
在 settings.py 我有以下內容:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'phonenumber_field',
'customer',
'contact',
'rest_framework',
'rest_framework.authtoken',
]
...
REST_FRAMEWORK = {
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
...
AUTH_USER_MODEL = 'customer.Customer'
...
我的序列化器(這里的聯系人是另一個模型):
class CustomerSerializer(serializers.ModelSerializer):
contacts = serializers.SerializerMethodField()
def get_contacts(self, obj):
from contact.serializers import ContactSerializer
from contact.models import Contact
return ContactSerializer(Contact.objects.filter(user=obj), many=True, read_only=True).data
class Meta:
model = Customer
fields = [
'pk',
'first_name',
'last_name',
'email',
'phone_number',
'created_at',
'updated_at',
'contacts',
]
我會錯過什么? 我已經在這里嘗試了所有解決方案: DRF auth_token: "non_field_errors": [ "Unable to log in with provided credentials."
我發現了這個問題 - 在https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example 之后,我能夠看到自定義用戶 model,你必須更新你的方式正在創建這些自定義用戶(通過 admin、auth 或其他方式)以確保密碼正確散列。 在此之后,我創建了一個自定義管理表單和一個自定義用戶管理器,可以正確覆蓋和處理 model 的保存:
def create_user(self, email, first_name, last_name, phone_number, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
phone_number=phone_number,
)
user.set_password(password)
user.save(using=self._db)
return user
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.