关于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这 ...
随机推荐
- Ubuntu 下安装mysqlclient报错
pip3 install mysqlclient 报错信息 问题描述: Complete output from command python setup.py egg_info: /bin/sh: ...
- NoSQL 数据库之MongoDB
1.MongoDB简介 1.1什么是MongoDB MongoDB 是一个跨平台的,面向文档的数据库,是当前 NoSQL 数据库产品中最热门的一种.它介于关系数据库和非关系数据库之间,是非关系数据库当 ...
- python操作日志的封装
前言 曾经转载过一篇关于python日志模块logging的详解 https://www.cnblogs.com/linuxchao/p/linuxchao-log.html, 虽然这篇文章是别人写的 ...
- ProC第二弹
一.提要 上文简单介绍了Windows下ProC配置开发,这次我们使用Linux平台再次配置Oracle ProC开发环境(RedHat Linux 9 + Oracle 92). <OR ...
- 线段树: CDOJ1598-加帕里公园的friends(区间合并,单点更新)
加帕里公园的friends Time Limit: 3000/1000MS (Java/Others) Memory Limit: 131072/131072KB (Java/Others) 我还有很 ...
- android自动化测试之Monkey--从参数讲解、脚本制作到实战技巧
视频: http://v.youku.com/v_show/id_XODcyMjM1MDA4.html?from=y1.2-1-87.4.4-1.1-1-2-3 PPT: http://www.doc ...
- navicat for mysql 在win7下设置定时计划之导出数据处理
navicat for mysql 在win7下设置定时计划之导出数据处理 博客分类: mysql navitcatmysql定时任务导出 前两篇记录了,navicat for mysql计划的入门 ...
- day03_13 多分支if语句及作业
猜年龄升级版 age_of_princal = 56 guess_age = int( input("请输入您猜测的年龄") ) if guess_age == age_of_pr ...
- Mysql读写分离实例
吐槽:前天刚加完MQ,这回加读写分离.我也是醉了,但是弄完之后,就发现,似乎没我想的那么复杂,真的!另外,昨天试了一下用swagger编写API文档,太方便了,加上Mock service测试.这两天 ...
- 简单使用EL进行标签的替换
package com.ceshi; public class HtmlShow { public static String transfer(String txt,String cssClass) ...