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. 二次剩余-Cipolla

    二次剩余 \(Cipolla\) 算法 概述 大概就是在模 \(p\) 意义下开根号,如求解方程\(x^2\equiv n(mod\ p)\). 这里只考虑 \(p\) 为素数的情况.若 \(p=2\ ...

  2. php 中的 Output Control 函数

    先看一个简单的例子 <?php ob_start(); echo 111; ob_clean(); echo 222; ob_start()开启ob缓存,然后111放进了ob缓存, 再调用ob_ ...

  3. [转]50个很棒的Python模块

    转自:http://www.cnblogs.com/foxhengxing/archive/2011/07/29/2120897.html Python具有强大的扩展能力,以下列出了50个很棒的Pyt ...

  4. javascript把json串转成对象

    // 这个是待转的json串 var jstr = "{'a':100,'b':'aaa'}"; // 经过下面语句把这个语句描述的对象数据,赋给这个m对象了 eval (&quo ...

  5. homeland 开源论坛系统搭建试用

    备注: 需要使用docker docker-compose   1. clone 代码 git clone https://github.com/ruby-china/homeland-docker. ...

  6. Træfɪk 服务发现解决方案

    Træfɪk is a modern HTTP reverse proxy and load balancer made to deploy microservices with ease. It s ...

  7. numpy中文件的存储和读取-嵩天老师笔记

    numpy中csv文件的存储和读取 CSV文件:(Comma‐Separated Value, 逗号分隔值) 一维和二维数组 存储 np.savetxt(frame,array,fmt='%.18e' ...

  8. ecmall在linux下的安装注意事项(转)

    今天跟ecshop客服胡娇沟通后知道ecmall基本配置是[LAMP] linux+apache+mysql+php,然后自己开始在linux下安装ecmall并做迁移,整理了一下中间碰到的问题.1. ...

  9. netstat 命令 与 ss 命令

    http://www.cnblogs.com/peida/archive/2013/03/11/2953420.html http://www.ttlsa.com/linux-command/ss-r ...

  10. Python——基础数据类型(补充)

    1.基础数据类型汇总补充 (1)小数据池:   为了节省空间,数字和字符串有,其他的没有[了解]   数字:-5---256之间的数字共用一个内存地址 #(1)i1 = i2 id(i1) == id ...