安装djangorestframework pip install djangorestframework
https://blog.csdn.net/lablenet/article/details/54667308
1. mysite/setting.py 配置token module
INSTALLED_APPS = ( ... 'rest_framework.authtoken' )
2.生成相关表
这种方法可以在SQL等数据库中创建与models.py代码对应的表,不需要自己手动执行SQ
python manage.py migrate
mysql> show tables;
+----------------------------+
| Tables_in_store |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| authtoken_token #生成此表
如果数据库有更改:
# 1. 创建更改的文件 python manage.py makemigrations # 2. 将生成的py文件应用到数据库 python manage.py migrate
!清空数据库中数据,留下空表:python manage.py flush
3.创建token
testapi/model.py
(1).第一种,配置所有,推荐第一种方案,sender指定settings.AUTH_USER_MODEL
# 为每个用户添加token值
from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # 为每个用户添加token验证 @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)
(2)第二种 sender指定实体
from django.contrib.auth.models import User @receiver(post_save, sender=User) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
当在views.py中进行 create_auth_token 的时候 当前view中的api就有token验证
from rest_framework.authtoken.models import Token def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
访问是就会需要token 值
{
"detail": "Authentication credentials were not provided."
}
推荐第一种方案
4. token rest framework 配置实现
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', #必须有 ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) }
5.客户端获取Token
(1)配置token url
在testapi下url.py 进行下面配置 :
urlpatterns = [ url(r'^list/', PartyList.as_view()), url(r'^listset/', party_set_list), url(r'^detail/(?P<pk>[0-9]+)$', PartyDetail.as_view()), url(r'^api-token-auth/', views.obtain_auth_token), # 获取token ]
(2)访问地址 : ip:port/testapi/api-token-auth
(3)返回值
{“Authorization”:“Token c4742d9de47d2cfec1dbe5819883ce6a3e4d99b”}
6.验证
在客户端的http 请求header 添加 Authorization 字段,比如
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
比如postman , 注意 : Token 字段与值 之间有空格。
7.android 使用okhttp 拦截器实现
OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.addInterceptor(loggingInterceptor); builder.addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (SPUtil.hasKey(SPConstrant.USER_TOKEN)) { //header add token request = request.newBuilder() .addHeader("Authorization","Token "+SPUtil.getSpString(SPConstrant.USER_TOKEN)) //伪获取 .build(); } return chain.proceed(request); } });
8.问题
出现下面问题:
{
"non_field_errors": [
"Unable to log in with provided credentials."
]
}
解决:
1.auth_user表中是否有该用户;
2.该用户的is_active是否为1;
3.authtoken_token表中是否有该用户的记录;
4.先创建超级用户,再进行创建用户
python manage.py createsuperuser
5.设置用户密码,可能是数据库存储的密码为明文
参考:https://blog.csdn.net/lablenet/article/details/54666953
以上来自:https://blog.csdn.net/lablenet/article/details/54667308
git:https://github.com/LABELNET/django-mysite-frist