Django中使用Token实现认证

  本文主要介绍django中token的生成与使用。 
  版本:

    python 3.5.2

    Django 2.0.3

    djangorestframework 3.7.7

 

创建Django项目

  1.安装django。https://docs.djangoproject.com/en/2.0/intro/tutorial01/

  2.安装djangorestframework  pip install djangorestframework

 

配置认证模式

  在settings中添加如下配置 

INSTALLED_APPS = [
    ......
    ......
    'rest_framework.authtoken'
    ......        
]

 

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

 

生成并使用Token

  Note:注意使用python manage.py migrate 生成对应的表

  在需要使用的地发引入  

from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from rest_framework import permissions

 

  1.在代码中创建Toke

token = Token.objects.create(user=...)
print token.key

  2.在接口中认证用户

  例如:

class DoingView(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)
    def get(self,request):
       doning....

  Note:使用 request.user 来获得请求的用户是谁。

 

  3.前端请求参数

   前端请求时需要在headers中带上如下参数,例如

   “Authorization”:“Token c4742d9de47d2cfec1dbe5819883ce6a3e4d99b”  

 

转载于:https://www.cnblogs.com/ShenLw/p/8608136.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值