I'm trying to use djoser with token authentication, but using django-rest-knox tokens.
I have set the TOKEN_MODEL
to knox.models.AuthToken
, and the rest framework's DEFAULT_AUTHENTICATION_CLASSES
to knox.auth.TokenAuthentication
.
I naïvely thought that this would be enough, but it seems that Djoser's inbuilt serializers (create token, and token), don't work properly with the knox tokens. I tried overriding them with custom serializers, but I didn't get anywhere (which is not to say it's not possible, just that I'm bad at this).
It occurred to me that perhaps I should try using Knox's own login views... Is that possible, or can they not be mixed like that? (I'm mainly asking because I don't want to get it to 'work', but find that I've actually introduced a security hole in doing so).
Settings:
DJOSER = {
"TOKEN_MODEL": "knox.models.AuthToken",
"SERIALIZERS": {"token": "users.serializers.TokenSerializer"},
}
Where users.serializers.TokenSerializer is:
class TokenSerializer(serializers.ModelSerializer):
auth_token = serializers.CharField(source="token_key")
class Meta:
model = settings.TOKEN_MODEL
fields = ("auth_token",)
This is only slightly modified from the original Djoser TokenSerializer. It was throwing an error that AuthToken objects did not have a key
attribute. Knox tokens seem to call it token_key
, so I replaced the line:
auth_token = serializers.CharField(source="key")
with auth_token = serializers.CharField(source="token_key")
Now, it doesn't throw an error, but it returns an empty token. Inspecting the actual db shows that it has saved a token with the correct user and creation time, but with 'null' for digest, salt, and token_key
Djoser
's namespace from your project settings. Serializer should overwrite under Serializer namespace in Djsoer settings. – Godmansettings.py
, i believe you did that appropriately but just want to check. – Godmansettings.TOKEN_MODEL
stands for, i mean is it knox.models.AuthToken or rest_framework.authtoken.models.Token. – Godman