安裝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