django restful token認證
阿新 • • 發佈:2019-01-28
一、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'