2

我正在使用Django 2.1.8构建简单的 API,并使用Django OAuth Toolkit提供安全性。我已经达到了用户只能在授权后使用 api 的地步,但我想将他的操作限制在他的数据上。

我已经使用 oauth2 建立了授权,它返回了access token

模型.py

class Client(AbstractUser):

    email = models.EmailField(
        verbose_name='email adress',
        max_length= 255,
        unique=True,
    )
    location = models.CharField(max_length=500, default="")

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    objects = ClientManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['location']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

视图.py

class SingleClientView(generics.RetrieveAPIView):
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated, TokenHasReadWriteScope]

是否有可能将返回的令牌与用户模型连接起来,所以每次有人使用 API 时,它都会过滤用户是否匹配所需的数据?或者 oauth 工具包是否自动以及如何访问它?

4

1 回答 1

2

您必须在文件中添加oauth2_provider.middleware.OAuth2TokenMiddleware中间件。settings.py这将自动为用户附加令牌所属的请求,您可以从request类似的地方访问它request.user

您可以相应地修改您的视图。

class SingleClientView(generics.RetrieveAPIView):
    queryset = Client.objects.all()
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated, TokenHasReadWriteScope]

    def get_object(self):
        return self.request.user
        # or any similar logic here..
于 2019-04-02T18:30:19.830 回答