在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後面有個空格
},