一始锚、TokenAuthentication
基于令牌的HTTP認(rèn)證方案恭金。令牌身份驗證適用于客戶端 - 服務(wù)器設(shè)置充蓝。
(1)settings中添加authtoken
INSTALLED_APPS = (
...
'rest_framework.authtoken'
)
ps:遷移數(shù)據(jù)庫 migrate
(2)設(shè)置權(quán)限
只能被注冊的用戶訪問
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參數(shù)獲取token
http://localhost:8000/api-token-auth
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
(5)設(shè)置請求
請求頭中添加token
'Authorization':'Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'