django项目前准备:三、更简单的使用rest_framwork的token验证

因为项目使用前后端分离技术,所以前端在本地调试需要访问后端数据的时候。

总采用JWT的方法挺麻烦。 我们可以在后端加入TokenAuthentication的认证中间件,这样前端用户访问后端数据就没有必要频繁地更新token。

详细官网地址: http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

具体操作如下:

1. settings中增加配置

INSTALLED_APPS = (
        ...
     'rest_framework.authtoken'
    )

2. 执行数据库migrate

3. 登陆admin,为开发账户生成token

4. 配置url接口

from rest_framework.authtoken import views
    urlpatterns += [
     url(r'^api-token-auth/', views.obtain_auth_token)
    ]

5. 测试,用户获取token

curl -X POST -H "Content-Type: application/json"   -d '{"username": "dev1", "password": "dev123456"}'   http://192.168.3.4/api-token-auth/ 

返回:{"token":"9809ba7e7a90b399e34b35a041653d248f6c6409"}

6. 测试,访问数据

curl -X GET http://192.168.3.4/XXXX/ -H 'Authorization: Token 9809ba7e7a90b399e34b35a041653d248f6c6409'

提示:身份信息未提供!

提示信息:To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication

 缺了啥配置呢?

 

7.因此,增加配置:

  'DEFAULT_AUTHENTICATION_CLASSES': (        # 测试环境开启,生产环境得关闭       
   'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
# 开发环境中用 'rest_framework.authentication.TokenAuthentication',
# 生产环境只开启JWT验证 'rest_framework_simplejwt.authentication.JWTAuthentication', ),

 

8. 再次请求,成功

 

posted on 2018-05-26 11:07  myworldworld  阅读(211)  评论(0编辑  收藏  举报

导航