在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后面有个空格
},