安装jwt库,简单快速的生成我们所需要的token
1.安装djangorestframe
pip install djangorestframe
2.在settings.py的INSTALLED_APPS中加入:
INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', # 设置token ... ]
安装jwt库,简单快速的生成我们所需要的token
1.安装JWT
pip install djangorestframework-jwt
2.配置jwt
# django-rest-framework设置 REST_FRAMEWORK = { 'PAGE_SIZE': 10, # 设置所有接口都需要被验证 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), }
解决api跨域请求
1.安装包
pip install django-cors-headers
2.配置django-cors-headers
INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 注意顺序 ... ) #跨域增加忽略 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = () CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', )
简单实用JWT
1.配置jwt有效时间
import datetime JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=300), # days=7 }
2.jwt验证
from rest_framework_jwt.views import obtain_jwt_token url(r'^api-token-auth/', obtain_jwt_token),
3.配置页面访问权限
from rest_framework_jwt.authentication import JSONWebTokenAuthentication class GoodsListViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): authentication_classes = (JSONWebTokenAuthentication,)
前端请求
1.使用post方法获取token并存入html的localStorage中
<script type="text/javascript"> function post_test() { $.post("http://10.127.48.204:8000/api-token-auth/",{ 'username':'earthchen', 'password':'xxxxxxxx' }, function(result){ if(result){ localStorage.token=result.token; 存入数据 } }) } </script>
2.在请求数据时需要在头部添加token
<script type="text/javascript"> function test(){ $.ajax({ headers:{ 'Authorization':'JWT '+localStorage.token //注意:jwt后面有个空格 }, type:"get", url:"http://10.127.48.204:8000/snippets/1/", success:function(result){ document.write(result.style); } }) } <script>