关于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 signalsOpen up a console window, navigate to your project dir, and enter the following command:
python manage.py migrate python manage.py makemigrationsTake 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
curlor 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这 ...
随机推荐
- MySQL数据库的多种备份与多种还原
一.备份 1.mysqldump 方法备份 mysqldump备份很简单,格式如下: mysqldump -u用户名 -p密码 数据库名> XX.sql 路径 例如: mysqldump -ur ...
- 安装ElasticSearch 6.1.1 head插件
https://blog.csdn.net/zoubf/article/details/79007908 主要参考了这个blog 才完成所有的配置,很好的参考资料
- Python学习笔记: 闭包
闭包的基本定义 在计算机科学中,闭包(英语:Closure),又称词法闭包(Lexical Closure)或函数闭包(function closures),是引用了自由变量的函数.这个被引用的自由变 ...
- Django之FileField字段
头像上传 在头像上传的时候,属于文件类型 首先视图函数获取的时候,request.FILES.get('文件名变量') avatar_obj = request.FILES.get('avatar') ...
- 【HIHOCODER 1589】回文子串的数量(Manacher)
描述 给定一个字符串S,请统计S的所有|S| * (|S| + 1) / 2个子串中(首尾位置不同就算作不同的子串),有多少个是回文字符串? 输入 一个只包含小写字母的字符串S. 对于30%的数据,S ...
- Linux学习-X Server 配置文件解析与设定
X server 的配置 文件都是预设放置在 /etc/X11 目录下,而相关的显示模块或上面提到的总总模块,则主要放置在/usr/lib64/xorg/modules . 比较重要的是字型文件与芯片 ...
- selenium2通过linkText/partialLinkText定位元素
通过linkText定位 linkText是根据链接的文本来定位,如下图,导航上全是链接 此时我想找“新闻”这个元素,那么我就可以使用linkText方式定位,语法: By.linkText(“新闻” ...
- Python之多线程与多进程(一)
多线程 多线程是程序在同样的上下文中同时运行多条线程的能力.这些线程共享同一个进程的资源,可以在并发模式(单核处理器)或并行模式(多核处理器)下执行多个任务 多线程有以下几个优点: 持续响应:在单线程 ...
- 【MySQL】MySQL基础
一.基本语法 [MySQL目录结构]●bin目录,存储可执行文件●data目录,存储数据文件●docs,文档●include目录,存储包含的头文件●lib目录,存储库文件●share,错误信息和字符集 ...
- Vmware复制完好的linux目录后网卡操作
目录 Vmware复制完好的linux目录后网卡操作 修改/etc/udev/rules.d/70-persistent-net.rules 修改网卡配置文件 重启查看 Vmware复制完好的linu ...