简体   繁体   English

重写 DRF 令牌身份验证

[英]Rewriting DRF token auth

I wanted to allow a user to have multiple tokens so decided to rewrite the Token model.我希望允许用户拥有多个令牌,因此决定重写令牌模型。 As result created结果创建

class TokenAuthentication(rest_framework.authentication.TokenAuthentication):
    model = Token

In my settings added to REST_FRAMEWORK在我的设置中添加到REST_FRAMEWORK

'DEFAULT_AUTHENTICATION_CLASSES': (
    'users.authentication.TokenAuthentication',
)

Also modified还修改了

class ObtainAuthToken(APIView):
    authentication_classes = ()
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = AuthTokenSerializer


    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        name = serializer.validated_data['name']
        token, created = Token.objects.get_or_create(user=user, name=name)
        return Response({'token': token.key})


obtain_auth_token = ObtainAuthToken.as_view()

and AuthTokenSerializer to return the name和 AuthTokenSerializer 返回名称

Finaly in the urls got最后在网址得到

url(r'^token-auth/', obtain_auth_token),

I think all is correct but keep getting the errors我认为一切都是正确的,但不断收到错误

 File "/home/me/code/python/OCManager/core/users/authentication.py", line 4, in <module>
    from rest_framework.views import APIView
ImportError: cannot import name 'APIView'

and

ImportError: Could not import 'users.authentication.TokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'APIView'.

Any hint what it could be?任何提示可能是什么?

The Token class modification is this: Token类修改是这样的:

class Token(rest_framework.authtoken.models.Token):
    # key is no longer primary key, but still indexed and unique
    key = models.CharField(_("Key"), max_length=40, db_index=True, unique=True)
    # relation to user is a ForeignKey, so each user can have more than one token
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, related_name='auth_tokens',
        on_delete=models.CASCADE, verbose_name=_("User")
    )
    name = models.CharField(_("Name"), max_length=64)

    class Meta:
        unique_together = (('user', 'name'),)

    def __str__(self):
        return self.user.username + " - " + self.name

I managed to find what was wrong.我设法找到了问题所在。 Having the TokenAuth extension in the same file was causing some import error, seems trying to import itself in other file.在同一个文件中使用 TokenAuth 扩展会导致一些导入错误,似乎试图在其他文件中导入自己。 The solution was moving解决方案正在移动

class TokenAuthentication(rest_framework.authentication.TokenAuthentication):
    model = Token

to another file到另一个文件

请确保你已经导入TokenAuthenticationrest_framework.authentication ,而不是从rest_framework.authToken

I was dealing with this error FOREVER.我一直在处理这个错误。 It turned out to have to do with tokens like everyone else was saying.事实证明,这与其他人所说的令牌有关。 This isn't exactly a "fix" but it got rid of the error for me:这不完全是“修复”,但它为我消除了错误:

I was using simplejwt and commented out the import: from rest_framework_simplejwt.tokens import RefreshToken And also commented out the function using the import.我正在使用 simplejwt 并注释掉导入: from rest_framework_simplejwt.tokens import RefreshToken并且还使用导入注释掉了函数。

My error was resolved after this.在这之后我的错误得到了解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM