django-rest-framework配置json web token

在Django中使用JSON Web Token来用于身份认证,与内置的TokenAuthentication方案不同,JWT身份验证不需要使用数据库来验证token。

下面来介绍一下在Django项目中怎么配置并使用:

1. 安装django-rest-framework-jwt

pip install djangorestframework-jwt

 2. settings.py

# django-rest-framework设置
REST_FRAMEWORK = {
    'PAGE_SIZE': 10,

    # 设置所有接口都需要被验证
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # 其他都是基本配置,这个是使用JSON Web认证的配置
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

# 设置token过期时间
import datetime
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300),
}

3. 添加URL

from rest_framework_jwt.views import obtain_jwt_token

url(r'^jwt-token/', obtain_jwt_token),

4. 在ViewSet中设置访问权限

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': unicode(request.user),  # `django.contrib.auth.User` instance.
            'auth': unicode(request.auth),  # None
        }
        return Response(content)

然后就是怎么获取token,以及怎么使用token来访问接口

获取token:

<script type="text/javascript">
 function post_test() {
        $.post("http://127.0.0.1:8000/api-token-auth/",{
            'username':'admin',
            'password':'xxxxxxxx'
        },
        function(result){
            if(result){
                localStorage.token=result.token;  存入数据
            }
        })
    }
</script>

postman

访问接口时需要在头部添加token

headers:{
   'Authorization':'JWT '+token  //注意:jwt后面有个空格
},

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值