一、TokenAuthentication
基於令牌的HTTP認證方案。令牌身份驗證適用於客戶端 - 服務器設置。
(1)settings中添加authtoken
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
ps:遷移數據庫 migrate
(2)設置權限
只能被註冊的用戶訪問
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
(3)生成令牌
from django.dispatch import receiver
from django.db.models.signals import post_save
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
(4)獲取令牌
from rest_framework.authtoken import views
urlpatterns += [
url(r'^api-token-auth/', views.obtain_auth_token)
]
通過post請求接口,傳遞username和password參數獲取token
http://localhost:8000/api-token-auth
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
(5)設置請求
請求頭中添加token
'Authorization':'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'