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

  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

 

时间: 2024-09-03 08:40:33

关于django rest framework里token auth的实现及答疑的相关文章

Django REST framework 的TokenAuth认证及外键Serializer基本实现

  一,Models.py中,ForeignKey记得要有related_name属性,已实现关联对象反向引用. app_name = models.ForeignKey("cmdb.App",related_name='deploy_app', verbose_name="App")   二,Settings.py文件中,加入对Django REST framework的基本设置. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CL

解决一个Django Rest Framework的JSON输出的小问题

  在服务器升级迁移过程中,遇到一个见了鬼的问题. 同样的一个API输出,在本机测试时和生产中一台机器上的输出为纯数据的json格式. 而在另一台生产机器上却为加了统计和跳转信息的另一种json格式. 由于前端用了vue.js作了数据的加载,如果同样的代码,那获取json中对象的信息显然就会发生问题. 解决BUG的时间来不及,也无法深入调试.可用以下代码,判断json中是否有存在对象来进行对象的赋值,可解决这个输出问题. 以后找时间还是深入研究一下这个DRF的输出机制吧. //此处兼容djang

Django Rest Framework 3.3.2 开发 RESTful API

Python Version:     2.7.10Django Version:     1.9REST framework 3.3.2 安装 pip install django pip install djangorestframework settings.py INSTALLED_APPS中引入rest_framework INSTALLED_APPS = [     'django.contrib.admin',     'django.contrib.auth',     'dja

如何向android的framework里添加新类

google对于所有的类和API,分为开放式和不开放式两种.所谓的开放式就是值javadoc所包含的,并不是java中有public和private,而是跟javadoc有关系,代码  没有关系. 在开放式的类中增加了一个变量,而又没隐藏,导致和原API的doc不一致造成的就会有错. 通过提示,有2个方法可以解决  该问题: 1.将新增加的变量或方法加上"@hide" 的注释,注意一点,加"@hide" 不是简简单单的/*@hide */就行了,标准的javadoc

如何向android的framework里添加新API

google对于所有的类和API,分为开放式和不开放式两种.所谓的开放式就是javadoc所包含的,并不是java中有public和private,而是跟javadoc有关系,代码没有关系. 在开放式的类中增加了一个变量,而又没隐藏,导致和原API的doc不一致造成的就会有错. 通过提示,有2个方法可以解决  该问题: 1.将新增加的变量或方法加上"@hide" 的注释,注意一点,加"@hide" 不是简简单单的/*@hide */就行了,标准的javadoc要这样

请问:C#常用的类,比如:Console类,它的代码是在我们安装的.NET FrameWork里,还是在VS2010里?

问题描述 请问:①C#常用的类,比如:Console类,它的代码是在我们安装的.NETFrameWork里,还是在VS2010里?②假设程序中有Console.WriteLine(),请问编译时,是将Console.WriteLine()的代码与程序其它代码链接组成一个完整的中间语言程序?还是程序在运行时当用到Console.WriteLine()的时候,就从.NETFrameWork里动态调用Console.WriteLine()? 解决方案 解决方案二:百度百科的图.解决方案三:.NETFr

django rest framework如何实现nest field显示,如何保存有外键的字段更新

一步一步深入了. 相关设置技巧如下: 直接nest field显示: class VersionPoolSerializer(serializers.ModelSerializer): site_name = serializers.ReadOnlyField(source='site_name.name') dep_version = DeployPoolSerializer(many=True, required=False, read_only=True) create_user = se

今天正好用MD5,.Net的Framework里有现成的。但是俺又找了个算法原型(VbScript)。一供其它语言参考

vbscript|参考|算法 <%' Derived from the RSA Data Security, Inc. MD5 Message-Digest Algorithm,' as set out in the memo RFC1321.''' ASP VBScript code for generating an MD5 'digest' or 'signature' of a string. The' MD5 algorithm is one of the industry stand

django从0到1搭建网站

曾经有人说我前端很水,那么在这一系列文章中我打算把前后端融合在一起来做一次网站的全面重构,希望可以把刚刚入行的同学带上正途   请尊重原创,转载请注明来源网站www.shareditor.com以及原始链接地址 聊聊工程 如今,数据科学家已经逐渐取代现在的"软件工程师"成为IT行业的主流职业,和"全民都在聊人工智能"一样,可能全部IT工作者都要天天研究算法.琢磨模型.跑数据.调参数.跑数据.调参数,那些被淘汰的"软件工程师"会真的成为民工一样的行