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):

  1. Do the following things BEFORE you create the superuser. Otherwise, the superuser does not get his/her token created.

  2. 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',
        )
    }
  3. 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

  4. 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)

  5. create a superuser with python manage.py createsuperuser. Now, take a look at theauthtoken_token table in your DB with select * from authtoken_token;, you should see a new entry has been added.

  6. 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
  7. (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的实现及答疑的更多相关文章

  1. django rest framework csrf failed csrf token missing or incorrect

    django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...

  2. 用Django Rest Framework和AngularJS开始你的项目

    Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...

  3. Django REST Framework API Guide 06

    本节大纲 1.Validators 2.Authentication Validators 在REST框架中处理验证的大多数时间,您将仅仅依赖于缺省字段验证,或在序列化器或字段类上编写显式验证方法.但 ...

  4. Django Rest framework 框架之认证使用和源码执行流程

    用这个框架需要先安装: pip3 install djangorestframework 如果写了一个CBV的东西,继承了View. # 继承Django里面View class APIView(Vi ...

  5. Django REST Framework API Guide 01

    之前按照REST Framework官方文档提供的简介写了一系列的简单的介绍博客,说白了就是翻译了一下简介,而且翻译的很烂.到真正的生产时,就会发现很鸡肋,连熟悉大概知道rest framework都 ...

  6. Django Rest Framework(2)

    目录 一.认证 二.权限 三.限制访问频率 四.总结 一.认证(补充的一个点) 认证请求头 #!/usr/bin/env python # -*- coding:utf-8 -*- from rest ...

  7. Django REST framework 源码剖析

    前言 Django REST framework is a powerful and flexible toolkit for building Web APIs. 本文由浅入深的引入Django R ...

  8. Django Rest Framework源码剖析(七)-----分页

    一.简介 分页对于大多数网站来说是必不可少的,那你使用restful架构时候,你可以从后台获取数据,在前端利用利用框架或自定义分页,这是一种解决方案.当然django rest framework提供 ...

  9. django使用RestFramework的Token认证

    今天实现的想法有点不正规: Django Rest framework的框架的认证,API都运行良好. 现在是要自己写一个function来实现用户的功能. 而不是用Rest 框架里的APIVIEW这 ...

随机推荐

  1. [BZOJ] 1907: 树的路径覆盖

    一个点必然被路径覆盖,根据是否为路径的端点分类 \(f[x][0]\)表示以\(x\)为根的子树,\(x\)不为端点的最小路径覆盖数 \(f[x][1]\)表示以\(x\)为根的子树,\(x\)为一条 ...

  2. 素材网站——mokuge

  3. Struts2和Spring MVC 区别 今天面试被问到了

    虽然说没有系统的学习过Spring MVC框架, 但是工作这么长时间, 基本上在WEB层使用的都是Spring MVC, 自己觉得Struts2也是一个不错的WEB层框架, 这两种框架至今自己还未有比 ...

  4. 如何在微信中发送"相册"文件时有选择性地显示视频文件

    相信很多微信用户在使用微信给朋友,同事发送相册中的文件时,微信会显示你手机中的视频文件,这样很不方便. 如果要完全不显示视频文件: 随便在手机中建立一个文件夹,名字叫 ".nomedia&q ...

  5. perl-basic-数组操作

    RT...直接看代码 my @stack = ("Fred", "Eileen", "Denise", "Charlie" ...

  6. centos新增或删除用户

    新增用户snzigod:adduser snzigod 修改snzigod密码:passwd snzigod 删除用户snzigod:userdel snzigod 删除用户以及用户目录: userd ...

  7. jmeter switch controller

    工作方式: Switch控制器通过给该控制器中的Value赋值,来指定运行哪个采样器.有两种赋值方式: 1.第一种是数值,Switch控制器下的子节点从0开始计数,通过指定子节点所在的数值来确定执行哪 ...

  8. HDU 5402 模拟 构造 Travelling Salesman Problem

    题意: 有一个n * m的数字矩阵,每个格子放着一个非负整数,从左上角走到右下角,每个格子最多走一次,问所经过的格子的最大权值之和是多少,并且输出一个路径. 分析: 如果n和m有一个是偶数的话,那么只 ...

  9. 换一种思维看待PHP VS Node.js

    php和javascript都是非常流行的编程语言,刚刚开始一个服务于服务端,一个服务于前端,长久以来,它们都能够和睦相处,直到有一天,一个叫做node.js的JavaScript运行环境诞生后,再加 ...

  10. SpriteKit-(SKNode)

    1.初始化 + (instancetype)node; + (nullable instancetype)nodeWithFileNamed:(NSString*)filename; 2.返回边界边框 ...