django TokenAuthentication 认证方式

本文介绍了如何在Django REST Framework中使用TokenAuthentication,并自定义认证方式以包含过期时间和缓存机制。内容包括在settings的配置中添加'app',以及编写包含过期检查的登陆视图函数。
摘要由CSDN通过智能技术生成
  • 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值