关于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这 ...
随机推荐
- cephfs 挂载 卸载
#挂载 sudo ceph-fuse -m 10.1.xx.231:6789,10.1.xx.232:6789,10.1.xx.233:6789 -r /MySQL-BK /data/backup # ...
- 使用python3调用MyQR库生成动态二维码(附源代码)
可生成普通二维码.带图片的艺术二维码(黑白与彩色).动态二维码(黑白与彩色). GitHub:https://github.com/sylnsfar/qrcode 中文版:https://github ...
- nrf51822微信开发入门学习笔记1:开始前的准备
参考:(id:love--baby)https://blog.csdn.net/hunhun1122/article/details/68922493 微信硬件平台:https://iot.weixi ...
- 爬虫制作入门学习笔记2:[转]python爬虫实例项目大全
WechatSogou [1]- 微信公众号爬虫.基于搜狗微信搜索的微信公众号爬虫接口,可以扩展成基于搜狗搜索的爬虫,返回结果是列表,每一项均是公众号具体信息字典. DouBanSpider [2]- ...
- Linux下的硬件驱动——USB设备(转载)
usb_bulk_msg函数 当对usb设备进行一次读或者写时,usb_bulk_msg 函数是非常有用的; 然而, 当你需要连续地对设备进行读/写时,建议你建立一个自己的urbs,同时将urbs 提 ...
- MediaStore类的使用
安卓系统会在每次开机之后扫描所有文件并分类整理存入数据库,记录在MediaStore这个类里,通过这个类就可以快速的获得相应类型的文件. 当然这个类只是给你一个uri,提取文件的操作还是要通过Curo ...
- php三种方式操作mysql数据库
php可以通过三种方式操作数据库,分别用mysql扩展库,mysqli扩展库,和mysqli的预处理模式分别举案例加以说明 1.通过mysql方式操作数据库 工具类核心代码: <?php cla ...
- vim 查找替换命令
http://vim.wikia.com/wiki/Search_and_replace
- jquery获得iframe内容的高度
html: <iframe name="rightgp" id="right_frame_h" src="/Poster/rightgp&quo ...
- 浅谈我所见的CSS命名风格
在两年工作中,总结一下我所见的css命名风格. 1.单一class命名 .header { width: 500px; } .item { text-indent: 20%; } 优点:简单,渲染效率 ...