一、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'
网友评论