代码之家  ›  专栏  ›  技术社区  ›  RockOnGom

Django Rest Framework需要JWT登录

  •  1
  • RockOnGom  · 技术社区  · 9 年前

    Http请求标头:

    class SystemUserView(View):
        @method_decorator(login_required)
        def get(self, request, user_id):
            users = list(User.objects.all().values('email', 'id', 'username'))
            return HttpResponse(HttpResponse(json.dumps(users), content_type="application/json"))
    

    URL:

    from django.conf.urls import url
    from . import views
    from .views import SystemUserView, UserAuthenticationView
    from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
    urlpatterns = [
        url(r'^$', views.index, name="index"),
        url(r'^login/?$', UserAuthenticationView.login, name="index"),
        url(r'^user/(?P<user_id>[0-9]+)/$', SystemUserView.as_view(), name='user'),
        url(r'^api-token-auth/', obtain_jwt_token),
        url(r'^api-token-refresh/', refresh_jwt_token),
        url(r'^api-token-verify/', verify_jwt_token),
    ]
    

    Python 3.6.2

    https://jpadilla.github.io/django-rest-framework-jwt

    1 回复  |  直到 6 年前
        1
  •  3
  •   Konstantin Schubert    8 年前
     class SystemUserView(View):
    

    看起来您正在导入Django视图,而不是DRF APIView

    下面是使用普通令牌身份验证的DRF视图示例。我还没有测试过它,您必须将其应用于JWT,但它应该会引导您走上正确的道路。

    from rest_framework import authentication, permissions
    from django.contrib.auth.models import User
    
    class ListUsers(APIView):
        """
        View to list all users in the system.
    
        * Requires token authentication.
        """
        authentication_classes = (authentication.TokenAuthentication,)
        permission_classes = (permissions.IsAuthenticated,)
    
        def get(self, request, user_id):
            """
            Return a list of all users.
            """
            users = list(User.objects.all().values('email', 'id', 'username'))
            return Response(users)
    

    DRF serializer 用于将用户对象转换为json。