关于django rest framework里token auth的实现及答疑
http://stackoverflow.com/questions/14838128/django-rest-framework-token-authentication
================================================
No, not in your models.py -- on the models side of things, all you need to do is include the appropriate app (rest_framework.authtoken
) in your INSTALLED_APPS
. That will provide a Token model which is foreign-keyed to User.
What you need to do is decide when and how those token objects should be created. In your app, does every user automatically get a token? Or only certain authorized users? Or only when they specifically request one?
If every user should always have a token, there is a snippet of code on the page you linked to that shows you how to set up a signal to create them automatically:
@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
(put this in a models.py file, anywhere, and it will be registered when a Django thread starts up)
If tokens should only be created at certain times, then in your view code, you need to create and save the token at the appropriate time:
# View Pseudocode
from rest_framework.authtoken.models import Token
def token_request(request):
if user_requested_token() and token_request_is_warranted():
new_token = Token.objects.create(user=request.user)
Once the token is created (and saved), it will be usable for authentication.
==============================
@ian-clelland has already provided the correct answer. There are just a few tiny pieces that wasn't mentioned in his post, so I am going to document the full procedures (I am using Django 1.8.5 and DRF 3.2.4):
Do the following things BEFORE you create the superuser. Otherwise, the superuser does not get his/her token created.
Go to settings.py and add the following:
INSTALLED_APPS = ( 'rest_framework', 'rest_framework.authtoken', 'myapp', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) }
Add the following code in myapp's models.py:
from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings # This code is triggered whenever a new user has been created and saved to the database @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance)
Alternatively, if you want to be more explicit, create a file named signals.py under myappproject. Put the code above in it, then in __init__.py, write
import signals
Open up a console window, navigate to your project dir, and enter the following command:
python manage.py migrate python manage.py makemigrations
Take a look in your database, a table named authtoken_token should be created with the following fields: key (this is the token value), created (the datetime it was created), user_id (a foreign key that references the auth_user table's id column)
create a superuser with
python manage.py createsuperuser
. Now, take a look at theauthtoken_token table in your DB withselect * from authtoken_token;
, you should see a new entry has been added.Using
curl
or a much simpler alternative httpie to test access to your api, I am using httpie:http GET 127.0.0.1:8000/whatever 'Authorization: Token your_token_value'
That's it. From now on, for any API access, you need to include the following value in the HTTP header (pay attention to the whitespaces):
Authorization: Token your_token_value
(Optional) DRF also provides the ability to return a user's token if you supply the username and password. All you have to do is to include the following in urls.py:
from rest_framework.authtoken import views urlpatterns = [ ... url(r'^api-token-auth/', views.obtain_auth_token), ]
Using httpie to verify:
http POST 127.0.0.1:8000/api-token-auth/ username='admin' password='whatever'
In the return body, you should see this:
{ "token": "blah_blah_blah" }
That's it!
============================
n Django 1.8.2 and rest framework 3.3.2 following all of the above was not enough to enable token based authentication.
Although REST_FRAMEWORK setting is specified in django settings file, function based views required @api_view decorator:
from rest_framework.decorators import api_view
@api_view(['POST','GET'])
def my_view(request):
if request.user.is_authenticated():
...
Otherwise no token authentication is performed at all
关于django rest framework里token auth的实现及答疑的更多相关文章
- django rest framework csrf failed csrf token missing or incorrect
django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...
- 用Django Rest Framework和AngularJS开始你的项目
Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...
- Django REST Framework API Guide 06
本节大纲 1.Validators 2.Authentication Validators 在REST框架中处理验证的大多数时间,您将仅仅依赖于缺省字段验证,或在序列化器或字段类上编写显式验证方法.但 ...
- Django Rest framework 框架之认证使用和源码执行流程
用这个框架需要先安装: pip3 install djangorestframework 如果写了一个CBV的东西,继承了View. # 继承Django里面View class APIView(Vi ...
- Django REST Framework API Guide 01
之前按照REST Framework官方文档提供的简介写了一系列的简单的介绍博客,说白了就是翻译了一下简介,而且翻译的很烂.到真正的生产时,就会发现很鸡肋,连熟悉大概知道rest framework都 ...
- Django Rest Framework(2)
目录 一.认证 二.权限 三.限制访问频率 四.总结 一.认证(补充的一个点) 认证请求头 #!/usr/bin/env python # -*- coding:utf-8 -*- from rest ...
- Django REST framework 源码剖析
前言 Django REST framework is a powerful and flexible toolkit for building Web APIs. 本文由浅入深的引入Django R ...
- Django Rest Framework源码剖析(七)-----分页
一.简介 分页对于大多数网站来说是必不可少的,那你使用restful架构时候,你可以从后台获取数据,在前端利用利用框架或自定义分页,这是一种解决方案.当然django rest framework提供 ...
- django使用RestFramework的Token认证
今天实现的想法有点不正规: Django Rest framework的框架的认证,API都运行良好. 现在是要自己写一个function来实现用户的功能. 而不是用Rest 框架里的APIVIEW这 ...
随机推荐
- 06grep与find命令详解
1. grep 命令 grep 命令用于在文本中执行关键词搜索,并显示匹配的结果,格式为"grep [选项][文件]". grep 命令的参数及其作用如下: -b 将可执行文件(b ...
- VMware12全新安装CentOS-6.9模板机(已优化)
1.从安装系统开始准备 安装中添加网卡 eth0 ip 10.0.0.210 netmask 24 gateway 10.0.0.254 DNS servers 223.5.5.5 eth1 ip 1 ...
- php 关于金额的几种计算方式
php 关于金额的几种计算方式 平常开始开发过程中,多多少少都会遇到点关于金额的计算,比如设置返利.提现手续费.折扣啊等等诸如此类的比例,然后再计算出之后的实际的费用. 下面,以折扣为例,来实现这类计 ...
- Install GStreamer on Ubuntu
apt-get install libgstreamer1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-p ...
- 购物车小程序(while循环,列表)
while True: salary = input("please input your salary:") if salary.isdigit(): salary=int (s ...
- STM32CUBEMX入门学习笔记3:HAL库以及STM32CUBE相关资料
微雪课堂:http://www.waveshare.net/study/article-629-1.html 之前的正点原子的例程资料 硬石科技stm32cube: 链接:https://pan.ba ...
- Aizu - 1386 Starting a Scenic Railroad Service (思维乱搞)
给你n个区间,求: 1:最多有多少区间与同一个区间相交. 2:相交部分的最大区间数目. Sample Input 1 4 1 3 1 3 3 6 3 6 Sample Output 1 2 2 Sam ...
- 某比赛小记1- 挑选第N大数字
题目:给1000个数字(有重复),从小到大排列后,挑选第N个数字. 数字文件如下:numbers.rar ,挑选第727个数字. java版本: //数组初始化 String str = " ...
- python基础学习笔记——列表及元组
列表 列表的介绍 列表是python的基础数据类型之一 ,其他编程语言也有类似的数据类型. 列表的索引和切片 列表和字符串一样也拥有索引: lst = ['刘德华','周润发','周杰伦','向华强 ...
- 总结:PHP值得注意的几个问题
1.除了变量和常量区分大小写外,其他的标识符不区分大小写(例如关键字,类名,函数名等): 2. >>>是无符号右移,不管第一位是0还是1,右移后前面都是补0: 3.在函数中传递数组, ...