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了。

相关推荐
啊阿狸不会拉杆24 分钟前
《Java 程序设计》核心知识点梳理与深入探究
java·开发语言·python·算法·php·intellij-idea
Kyle199427 分钟前
RollCode:高效低代码开发新体验
前端
这是个栗子28 分钟前
【Node.js安装注意事项】-安装路径不能有空格
前端·npm·node.js
源力祁老师29 分钟前
外部系统获取Odoo数据最便捷的方式
开发语言·前端·javascript
用户97141718142731 分钟前
picker-view选中框不居中
前端
YGY_Webgis糕手之路31 分钟前
Cesium 快速入门(十) JulianDate(儒略日期)详解
前端·gis·cesium
燕山石头1 小时前
解决 IntelliJ IDEA Build时 Lombok 不生效问题
java·前端·intellij-idea
chancygcx_1 小时前
前端核心技术Node.js(二)——path模块、HTTP与模块化
前端·http·node.js
YGY_Webgis糕手之路1 小时前
Cesium 快速入门(三)Viewer:三维场景的“外壳”
前端·gis·cesium