Django JWT Auth-过滤特定用户的响应

时间:2019-03-20 10:04:08

标签: python django jwt django-rest-framework-jwt

我正在Django项目中实现JWT身份验证,此刻,我陷入了一个想通过JWT过滤响应数据的部分。

我想在Django视图中获取有关已认证用户的特定数据。如何获得此过滤数据?

以下是“设置”视图的示例。

Views.py

Class SettingsViewSet(viewsets.ModelViewSet):
    # here I'd like to decode my JWT token 
    # and filter the response data for particular user 
    queryset = Settings.objects.all()
    serializer_class = SettingsSerializer

urls.py

# ...
router.register(r'api/settings', SettingsViewSet)
# ...
urlpatterns = [
    # ...
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'),
    # ...
]

Serializers.py

class SettingsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Settings 
        fields = ('id', 'name', 'value', 'description', 'office')

settings.py

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework_simplejwt.authentication.JWTAuthentication',
],

}

这是我用来获取服务器响应的curl命令:

curl -H ‘Content-Type: application/json’ http://127.0.0.1:8000/api/settings/ -H ‘Authorization: Bearer <Here goes JWT token for particular user>’ 

作为回应,我获得了所有用户的所有设置。我只想获取经过身份验证的数据。

1 个答案:

答案 0 :(得分:1)

当前登录的用户实例应由您使用的库自动添加到请求对象中。这样,您可以覆盖 get_queryset 方法,以通过当前登录的用户过滤响应,前提是您在“设置”模型中有一个用户字段:

class SettingsViewSet(viewsets.ModelViewSet):
    queryset = Settings.objects.all()
    serializer_class = SettingsSerializer

    def get_queryset(self):
        queryset = Settings.objects.filter(user=self.request.user)
        return queryset