這里用到django-rest-framework-jwt這個(gè)庫?? https://github.com/GetBlimp/django-rest-framework-jwt
按流程圖來
先通過wx.login()獲取code,再通過我們后臺(tái)配置的接口獲取openid和session_key
// 登錄 wx.login({ success: res => { console.log(res) // 發(fā)送 res.code 到后臺(tái)換取 openId, sessionKey, unionId wx.request({ url: api.GET_OPENID, // data: { js_code: res.code }, success: function (res) { var openid = res.data.openid var session_key = res.data.session_key //獲取openid,session_key //后臺(tái)用戶表保存 wx.request({ url: api.USER, method: "POST", data: { openid : openid, session_key : session_kay }, success: function (res) { if (res.data.status == 'success') { //在緩存中保存用戶id和openid備用 wx.setStorage({ key: 'userid', data: res.data.userid, }); wx.setStorage({ key: 'openid', data: openid, }) } else { wx.showModal({ title: '提示', showCancel: false, content: '獲取openid失敗', }) } } }) } }) } })
在這里的用戶表最好是在django自帶的user表上進(jìn)行字段拓展,不然重寫起來會(huì)很麻煩,拓展方法如下
from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): """ 用戶新增字段 """ name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名")
下面是django的user默認(rèn)字段,需要保存用戶頭像,用戶省市等字段只要在原有基礎(chǔ)上新增即可
生成3rd session
先在后臺(tái)配置jwt
安裝
pip install djangorestframework-jwt
在你的settings.py,添加JSONWebTokenAuthentication到Django REST框架DEFAULT_AUTHENTICATION_CLASSES。
REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # <------- 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } #JWT設(shè)置過期時(shí)間,具體配置查看文檔 JWT_AUTH = { 'JWT_VERIFY_EXPIRATION': False } #在您urls.py添加以下URL路由以啟用通過POST獲取令牌包括用戶的用戶名和密碼。 from rest_framework_jwt.views import obtain_jwt_token #... urlpatterns = [ '', # ... url(r'^api-token-auth/', obtain_jwt_token), ]
通過POST用戶的用戶名和密碼獲取token
wx.request({ url: api.api-token-auth,//url配置 method: 'POST', data: { 'username': openid, //這里我是用openid當(dāng)作用戶名 'password': session_key //用session_key當(dāng)作密碼 }, success: function(jwt) { //jwt格式:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InhpZWhhbyIsImV4cCI6MTUzNTM3ODQ2OCwiZW1haWwiOiIzNDg2OTg1ODhAcXEuY29tIn0.8rXFK_K2q8474LxYrCuuNJT93PkZMzi1JX6fVproXrE //前面是base64后面是簽名,用.隔開 //將jwt_token放入緩存?zhèn)溆? var jwt_token = jwt.data.token wx.setStorageSync('jwt_token', jwt_token) self.globalData.jwt_token = jwt_token } })
后端配置時(shí)需要加上authentication_classes進(jìn)行認(rèn)證
from rest_framework.permissions import IsAuthenticated from rest_framework_jwt.authentication import JSONWebTokenAuthentication # 商品表 class goodsViewSet(viewsets.ModelViewSet): queryset = Goods.objects.all() serializer_class = goodsSerializers filter_class = GoodsFilter filter_backends = (DjangoFilterBackend, filters.SearchFilter) search_fields = ('name',) #認(rèn)證配置 permission_classes = (IsAuthenticated,) authentication_classes = (JSONWebTokenAuthentication,)
使用方法
在請求加了認(rèn)證的view時(shí),如果不在head中帶入jwt_token,請求401
在header中帶入請求數(shù)據(jù)成功
//從緩存中取出jwt_token,并按文檔用法拼接,在header中帶入Authorization // JWT +jwt_token var jwt_token = 'JWT ' + wx.getStorageSync('jwt_token') wx.request({ url: 'http://127.0.0.1:8000/mall/goods/', header:{ 'Authorization': jwt_token }, success:function(res){ //成功請求到商品數(shù)據(jù) console.log(res) } })
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
