REST框架中的Token认证不像Session认证一样,它是没有办法设置过期时间的,但是有时我们需要对Token做过期验证,比如说用户在A设备登陆之后获取一个Token,如果用户在没有清空浏览器缓存的情况下,Token将一直保存在缓存中,一周后在访问依旧有效,但我们并不希望这样,我们觉得Token认证应该和Session一样都有过期时间,过期之后作废。

  1. 首先,看下TokenAuthentication模块的源码如下:

     class TokenAuthentication(BaseAuthentication):
    keyword = 'Token'
    model = None def get_model(self):
    if self.model is not None:
    return self.model
    from rest_framework.authtoken.models import Token
    return Token def authenticate(self, request):
    auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode():
    return None if len(auth) == 1:
    msg = _('Invalid token header. No credentials provided.')
    raise exceptions.AuthenticationFailed(msg)
    elif len(auth) > 2:
    msg = _('Invalid token header. Token string should not contain spaces.')
    raise exceptions.AuthenticationFailed(msg) try:
    token = auth[1].decode()
    except UnicodeError:
    msg = _('Invalid token header. Token string should not contain invalid characters.')
    raise exceptions.AuthenticationFailed(msg) return self.authenticate_credentials(token) def authenticate_credentials(self, key): # key=前端在请求头传过来的Token
    model = self.get_model() # 获取Token模块
    try:
    token = model.objects.select_related('user').get(key=key) # 通过key获取Token
    except model.DoesNotExist:
    raise exceptions.AuthenticationFailed(_('Invalid token.')) # 如果没有就报错 if not token.user.is_active:
    raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) # 如果用户没有激活也报错 return (token.user, token) def authenticate_header(self, request):
    return self.keyword # 然后把Token和登录的用户返回给View

上面有注解的地方是关键。 过期验证,就相当于多加一个判断,只要继承该类,然后重写authenticate_credentials方法即可。以下是我实现的例子,以expiringTokenAuthentication.py保存。

from rest_framework.authentication import TokenAuthentication
from django.utils.translation import ugettext_lazy as _
from rest_framework import exceptions
from django.utils import timezone
from datetime import timedelta
from django.conf import settings
class ExpiringTokenAuthentication(TokenAuthentication):
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.select_related('user').get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed(_('Invalid token.'))
if not token.user.is_active:
raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) if timezone.now() > (token.created + timedelta(DAYS)): # 重点就在这句了,这里做了一个Token过期的验证,如果当前的时间大于Token创建时间+DAYS天,那么久返回Token已经过期
raise exceptions.AuthenticationFailed(_('Token has expired'))
return (token.user, token)

以此类推, 要对token进行类似的判断,都可以按上面的代码进行仿写。

Django restframework Token拥有不过期的认证的更多相关文章

  1. Django:RestFramework之-------认证

    3 restframework-认证 3.1APIView 认证: 认证是否已经登陆,如果已经登陆返回元组,如果没有登陆报错 源码流程: 执行dispatch方法: def dispatch(self ...

  2. django restframework 的日常使用

    本文讨论 django restframework 的日常使用,满足常用 api 编写的需求,比如 List, Detail, Update, Put, Patch 等等.探讨 django rest ...

  3. 基于token的多平台身份认证架构设计

    基于token的多平台身份认证架构设计 1   概述 在存在账号体系的信息系统中,对身份的鉴定是非常重要的事情. 随着移动互联网时代到来,客户端的类型越来越多, 逐渐出现了 一个服务器,N个客户端的格 ...

  4. django restframework

    一.django restframework 请求流程源码剖析 上面的认证一个流程是rest_framework的关于APIauth的认证流程,,这个流程试用权限.频率.版本.认证.这个四个组件都是通 ...

  5. django restframework jwt

    既然要来学习jwt(json web token),那么我们肯定是先要了解jwt的优势以及应用场景--跨域认证. $ pip install djangorestframework-jwt 传统coo ...

  6. Django组件 - cookie、session、用户认证组件

    一.cookie 1.会话跟踪技术 1)什么是会话跟踪技术 我们需要先了解一下什么是会话!可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打个电话 ...

  7. [原创]django+ldap+memcache实现单点登录+统一认证

    前言 由于公司内部的系统越来越多,为了方便用户使用,通过django进行了单点登录和统一认证的尝试,目前实现了django项目的单点登录和非django项目的统一认证,中间波折挺多,涉及的技术包括dj ...

  8. Django Rest Framework源码剖析(一)-----认证

    一.简介 Django REST Framework(简称DRF),是一个用于构建Web API的强大且灵活的工具包. 先说说REST:REST是一种Web API设计标准,是目前比较成熟的一套互联网 ...

  9. Django Restframework 实践(一)

    具备以下知识: django http://www.cnblogs.com/menkeyi/p/5882464.html http://www.cnblogs.com/menkeyi/p/588245 ...

随机推荐

  1. BZOJ1853 Scoi2010 幸运数字 【枚举+容斥】

    BZOJ1853 Scoi2010 幸运数字 Description 在中国,很多人都把6和8视为是幸运数字!lxhgww也这样认为,于是他定义自己的“幸运号码”是十进制表示中只包含数字6和8的那些号 ...

  2. 好用的 convert freestyle jenkins jobs to pipeline 插件使用

    1. 安装      安装,重启即可,非常简单   2. 使用     原有配置,主要列出执行     生成的jenkins pipeline   3. 构建效果   4. 参考资料 https:// ...

  3. 用vs2010编译vs2013建的工程

    第一步,用文本打开,修改.sln文件 原始: Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2 ...

  4. php+ajax+jquery 定时刷新页面数据

    testajax.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  5. Android照片墙完整版,完美结合LruCache和DiskLruCache

    转载地址:http://blog.csdn.net/guolin_blog/article/details/34093441#comments 在上一篇文章当中,我们学习了DiskLruCache的概 ...

  6. 1.远程仓库的使用(github)

    1.登录Github,新建一个仓库(远程仓库) (1)使用Github账号密码登录 (2)点击+旁边的小三角,选择new repository--输入repository name--点击create ...

  7. 7个去伪存真的JavaScript面试题

    1.创建JavaScript对象的两种方法是什么? 这是一个非常简单的问题,如果你用过JavaScript的话.你至少得知道一种方法.但是,尽管如此,根据我的经验,也有很多自称是JavaScript程 ...

  8. 使用JDK合成照片

    原图(工程所在目录7098849.jpg): 头像(工程所在目录20181023201750.jpg): 开始合成(执行如下main方法): public static void main(Strin ...

  9. Renesas CAT CONFIG

    CAT CELL "sf_cellular_api.h" typedef enum e_sf_cellular_at_cmd_index { SF_CELLULAR_AT_CMD_ ...

  10. cocos2dx 3.0 编译工程

    下载完2dx,运行setup.py,参考设置ANDROID_SDK,NDK_ROOT,ANT_ROOT变量 创建工程 cocos new testGame -p com.game.test -l cp ...