您的位置:首页 > 编程语言 > Go语言

django-TokenAuthentication

2017-11-09 17:02 239 查看
因为项目使用前后端分离技术,所以前端在本地调试需要访问后端数据的时候。总采用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'


提示:身份信息未提供!

7. 缺了啥配置呢?


To use the TokenAuthentication scheme you'll need to configure the authentication classes to include TokenAuthentication


8. 上述这句话,非常不起眼,被这个问题搞过两回了,这次记录一下,下次别再别操!


因此,增加配置:

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


9. 再次请求,成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django token 认证 restful