- settings的配置
INSTALLED_APPS = [
.....
.....
'rest_framework.authtoken'
]
因为token认证的方式 ,会在数据库中生成一个token表,存储token值,并与user关联,需要把'rest_framework.authtoken',写入app中
- 自定义一个token认证方式
django restframework 自带有一个TokenAuthentication的认证方式,不过自带模块生成的token没有过期时间.
首先,可以仿照TokenAuthentication,自定义一个判断过期时间的认证方式,
代码如下:
import pytz
from rest_framework.authentication import SessionAuthentication
from django.utils.translation import ugettext_lazy as _
from django.core.cache import cache
import datetime
from rest_framework.authentication import BaseAuthentication,TokenAuthentication
from rest_framework import exceptions
from rest_framework.authtoken.models import Token
from rest_framework import HTTP_HEADER_ENCODING
# 获取请求头里的token信息
def get_authorization_header(request):
"""
Return request's 'Authorization:' head