django rest_framework 前端网页实现Token认证

rest_framework提供了几种认证方式:Session、Token等。Session是最简单的,几乎不用写任何代码就可以是实现,Token方式其实也不复杂,网上的教程一大把,但是最后都是用Postman这类工具来实现API调用的,通过这类工具来增加HTTP头信息以回传Token。那么真正的前端网页应该怎么办呢?网上基本上就是基于Aixos来实现的,但是我就不想用Vue,纯Javascript是不能改写HTTP头的。怎么办?

首先,看一下TokenAuthentication的源码:

复制代码
auth = request.META.get('HTTP_AUTHORIZATION', b'')

它是从HTTP头中读取Authorization,其中是的内容Token(固定字) Token(值)。

那既然JavaScript不能改写头,但是能用cookie啊,所以我就通过自定义TokenAuthentication类,读取Cookie来实现。

  1. 用户登录之后先创建Token,并返回给前端。

  2. 前端把Token保存到Cookie。

复制代码
$.ajax({
    url: "login",
    type:'POST',
    data: {'username':username,'password':password},
    dataType: "json",
    success: function (data) {   //请求成功后执行的操作
        if (data.status == "SUCCESS") {
            //localStorage.setItem('token',data.token);
            $.cookie('token', data.token);
            window.location.href = '/';
        }
        else{
            alert('Invalid username or password.');
        }
    }
});

这样每次发起HTTP请求时都会把Token带上

  1. 在logout的时候把Token删除。防止失效Token仍然可以使用。
复制代码
def logout_view(request):
    request.user.auth_token.delete()
    logout(request)

    return redirect('login')
  1. 写一个自定义的TokenAuthentication类:
复制代码
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.authtoken.models import Token

class CustomTokenAuthentication(BaseAuthentication):
    keyword = 'token'

    def authenticate(self, request):
        cookie_token = request.COOKIES.get(self.keyword)

        if cookie_token is None:
            raise AuthenticationFailed('No Token Found in Cookies!')

        try:
            user_token = Token.objects.get(key=cookie_token)
            if user_token is None:
                raise AuthenticationFailed('No Token Found for Current User!')

            return (user_token.user, user_token)
        except Token.DoesNotExist:
            raise AuthenticationFailed('Token in cookie is invalidate!')

当Token未提供或者无效时,直接抛出AuthenticationFailed异常

  1. 讲自定义的类放入项目的settings,否则不生效:
复制代码
REST_FRAMEWORK = {
   'DEFAULT_AUTHENTICATION_CLASSES': (
       'bid_request_system_app.commons.authentications.CustomTokenAuthentication',
       'rest_framework.authentication.SessionAuthentication',
   ),
}
  1. 在相对应的view方法前面加上相应的注解:
复制代码
@api_view(['GET', 'POST'])
@csrf_exempt
@login_required()
@authentication_classes([CustomTokenAuthentication])
@permission_classes([IsAuthenticated, IsAdminUser])
def department_management_view(request):

这样的话就OK了。

相关推荐
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
前端小万5 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python