我正在使用 Django 2.1.8 构建简单的API,并通过 Django OAuth Toolkit 提供安全性。我已经达到了用户只能在授权后才能使用api的地步,但我想仅将他的操作限制为他的数据。
我使用oauth2建立了授权,该授权返回了我访问令牌。
models.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
views.py
class SingleClientView(generics.RetrieveAPIView):
queryset = Client.objects.all()
serializer_class = ClientSerializer
permission_classes = [IsAuthenticated, TokenHasReadWriteScope]
是否有可能将返回的令牌与用户模型连接起来,所以每次有人使用API时,如果用户匹配所需数据,它都会进行过滤?还是oauth工具箱会自动添加以及如何访问?
答案 0 :(得分:0)
您必须在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..