1、在setting.py 中增加設置
'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework.authentication.BasicAuthentication',#基本的用戶名密碼驗證'rest_framework.authentication.SessionAuthentication','rest_framework.authentication.TokenAuthentication',# token 認證],
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','course.apps.CourseConfig','rest_framework','rest_framework.authtoken',#DRF 自帶token認證
]
2、生成token 表
python manage.py makemigration
python manage.py migrate
3、寫一個信號函數 使得創建用戶時 自動創建token .在views.py中增加
from django.db.models.signals import post_save
from django.dispatch import receiver
#from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.authtoken.models import Token#@receiver(post_save,sender = User) Django 的信號機制
@receiver(post_save,sender = settings.AUTH_USER_MODEL)
def generate_token(sender,instance=None,created=False,**kwargs):if created:Token.objects.create(user=instance)
4、創建獲取token用的路由
from django.contrib import admin
from django.urls import path,include
from rest_framework.authtoken import views
urlpatterns = [path('api-token-auth', views.obtain_auth_token),#獲取token的接口path('admin/', admin.site.urls),path('api-auth/', include('rest_framework.urls')),path('course/',include('course.urls')),
]
5、使用方法? 使用post 方法訪問api-token-auth 方法??
{“username":"xxxx","password":"xxxxx"
}
6、獲取到token .就可以使用token認證訪問接口了