django使用RestFramework的Token认证
今天实现的想法有点不正规:
Django Rest framework的框架的认证,API都运行良好。
现在是要自己写一个function来实现用户的功能。
而不是用Rest 框架里的APIVIEW这些,不涉及序列化这事。
那么,我们如何来实现这种情况下的token认证呢?
参考文档:
https://www.jianshu.com/p/078fb116236e
一,先写一个用于认证的类
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
def get_authorization_header(request):
auth = request.META.get('HTTP_AUTHORIZATION', b'')
if isinstance(auth, type('')):
auth = auth.encode(HTTP_HEADER_ENCODING)
return auth
# 自定义的TokenAuthentication认证方式
class CustomTokenAuthentication(BaseAuthentication):
model = Token
def authenticate(self, request):
auth = get_authorization_header(request)
if not auth:
return None
try:
token = auth.decode()
except UnicodeError as e:
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):
try:
token = self.model.objects.get(key=key[6:])
except self.model.DoesNotExist as e:
raise exceptions.AuthenticationFailed('auth fail.')
return token.user, token
def authenticate_header(self, request):
return 'Token'
二,在调用及验证时,用如下方法:
def test_deploy(request):
if request.method == 'POST':
try:
aa = TokenAuthentication()
user_name, token = aa.authenticate(request)
except Exception as e:
print(e)
result = {'return': 'fail', 'message': "auth fail."}
return JsonResponse(result, status=403)
三,那我们在客户端的requests库调用代码如下:
url = "http://127.0.0.1:8000/deploy/test_deploy/"
mytoken = "xxxx0821232"
headers = {'Authorization': 'Token {}'.format(mytoken)}
payload = {'name': 'SxxxE'}
r = requests.post(url, data=payload, headers=headers)
print(r.status_code)
print(r.text)
由于,我们就可以在视图里进行认证,并进行业务逻辑处理,并自定义返回的东东~~
django使用RestFramework的Token认证的更多相关文章
- 【django后端分离】Django Rest Framework之认证系统之redis数据库的token认证(token过期时间)
1:登录视图 redis_cli.py文件: import redis Pool= redis.ConnectionPool(host='localhost',port=6379,decode_res ...
- Django Rest framework 框架之认证使用和源码执行流程
用这个框架需要先安装: pip3 install djangorestframework 如果写了一个CBV的东西,继承了View. # 继承Django里面View class APIView(Vi ...
- Django 之 restframework 频率组件的使用
Django 之 restframework 频率组件的使用以及源码分析 频率组件的使用 第一步,先写一个频率类,继承SimpleRateThrottle 一定要在这个类里面配置一个scop='字符串 ...
- python 全栈开发,Day97(Token 认证的来龙去脉,DRF认证,DRF权限,DRF节流)
昨日内容回顾 1. 五个葫芦娃和三行代码 APIView(views.View) 1. 封装了Django的request - request.query_params --> 取URL中的参数 ...
- Django REST framework 之JWT认证
Json Web Token 1.JWT简介 JWT 是一个开放标准(RFC 7519),它定义了一种用于简洁,自包含的用于通信双方之间以 JSON 对象的形式安全传递信息的方法.JWT 可以使用 H ...
- django rest_framework 实现用户登录认证
django rest_framework 实现用户登录认证 1.安装 pip install djangorestframework 2.创建项目及应用 创建过程略 目录结构如图 3.设置setti ...
- Django(65)jwt认证原理
前言 带着问题学习是最有目的性的,我们先提出以下几个问题,看看通过这篇博客的讲解,能解决问题吗? 什么是JWT? 为什么要用JWT?它有什么优势? JWT的认证流程是怎样的? JWT的工作原理? 我们 ...
- 42.JSON Web Token认证
JSON Web Token认证介绍 简称JWT认证,一般用于用户认证 JWT是一种相当新的标准,可用于基于token的身份验证 与内置的TokenAuthentication方案不同,JWT不需要使 ...
- 基于Token认证的多点登录和WebApi保护
在文章中有错误的地方,或是有建议或意见的地方,请大家多多指正,邮箱: linjie.rd@gmail.com 一天张三,李四,王五,赵六去动物园,张三没买票,李四制作了个假票,王五买了票,赵六要直接F ...
随机推荐
- Linux运维二:CentOS6.6系统安装后的基本配置与优化
CentOS6.6系统安装完成后还需要做一些配置与优化: 一:Linux内核版本号介绍 查看内核版本: [root@Gin scripts]# uname -r 2.6.32-504.el6.x86_ ...
- UITableViewCell在非Nib及Cell重用下设置CellStyle
在UITableViewController(实现了UITableViewDataSource)下需要实现 - (UITableViewCell *)tableView:(UITableView *) ...
- Django 2.0.1 官方文档翻译: 编写你的第一个 Django app,第七部分(Page 12)
编写你的第一个 Django app,第七部分(Page 12)转载请注明链接地址 本节教程承接第六部分(page 11)的教程.我们继续开发 web-poll应用,并专注于自定义django的自动生 ...
- CodeForces 714A
Description Today an outstanding event is going to happen in the forest — hedgehog Filya will come t ...
- CodeForces 816B 前缀和
To stay woke and attentive during classes, Karen needs some coffee! Karen, a coffee aficionado, want ...
- url参数用&拼接并且按照字母顺序排序方法
private string urlParamManager(JObject postArray, bool flag) { ArrayList keys = new ArrayList(); for ...
- IIS8.0 配置应用程序初始化功能
IIS进程回收后,第一次访问会超级慢,这对于用户是不能接受的,怎么解决这个问题? 我们不能设置IIS不回收进程,因为这样可能会导致IIS内存泄漏.有效的方法时,尽量在业务空闲时间回收进程,回收后立刻预 ...
- 如何在ie6/ie7/ie8中实现iframe背景透明
最近做了一个项目,涉及到ie8iframe背景透明的问题,做了老半天,才把它搞定的,现在把我的经历贴出来和大家分享: 众所周知的根据W3C CSS 2.1 规范规定,''''background-co ...
- mysql远程连接数据库
配置mysql允许远程连接的方法. (1)查看3306端口状态 netstat -an | grep 3306 (2)修改mysql配置文件 ubuntu系统:vim /etc/mysql/mysql ...
- Git 创建仓库【转】
转自:http://www.runoob.com/git/git-create-repository.html Git 创建仓库 本章节我们将为大家介绍如何创建一个 Git 仓库. 你可以使用一个已经 ...