pip install djangorestframework-jwt
INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', # 设置token ... ] REST_FRAMEWORK = { ... # 添加JWT全局认证 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } # Custom token expiration Import datetime JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=86400),
from django.contrib.auth.models import Group from rest_framework.permissions import IsAuthenticated from .serializers import UserGroupsSerializer class UserGropInfoViewset(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Group.objects.all() serializer_class = UserGroupsSerializer
routing
# 当前app下的router.py from rest_framework.routers import DefaultRouter from .views import UserGropInfoViewset group_router = DefaultRouter() group_router.register('GroupsInfo',UserGropInfoViewset,base_name='GroupsInfo') # Global url.py # in your urls.py file configuration is as follows: from rest_framework.routers Import defaultrouter route = DefaultRouter() from users.router import group_router route.registry.extend(group_router.registry) # 配置jwt路由 from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^', include(route.urls)), url(r'^api-auth',include('rest_framework.urls',namespace='rest_framework')), # 使用jwt验证 url(r'^api-token-auth/', obtain_jwt_token),
#drf own token authentication mode
url (r '^ api-token -auth /', views.obtain_auth_token),