編程學習網 > 數據庫 > django框架開發小程序如何處理認證問題(django框架實戰開發小程序)
2022
09-17

django框架開發小程序如何處理認證問題(django框架實戰開發小程序)


在使用django框架開發小程序時,會遇到一些認證問題,比如微信小程序不支持賬戶名、密碼登錄,也不支持session登錄,故采用Django作為后臺時,一種可行的方法就是使用JWT登錄。

本文采用的是Simple JWT來實現


安裝

pip install djangorestframework-simplejwt

配置項目settings

在restful_framework的配置:

# settings.py

'DEFAULT_AUTHENTICATION_CLASSES': (
       'rest_framework_simplejwt.authentication.JWTAuthentication',
       'rest_framework.authentication.TokenAuthentication',
       'rest_framework.authentication.BasicAuthentication',
       'rest_framework.authentication.SessionAuthentication',
  )

主要是加上rest_framework_simplejwt.authentication.JWTAuthentication

這樣django會自動檢查是否帶有token。

配置UR

配置好url,在我的項目里是用來測試JWT能否正常登錄用的,官方文檔里有如下方法

# urls.py
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView

urlpatterns = [
      ...
       path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
       path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
       path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),
]
進行測試的代碼如下(也可以用來展示用法):



def test_get_token(self):
   url = '/web-api/token/'

   response = self.client.post(url, user_info, format='json')
   self.assertEqual(response.status_code, status.HTTP_200_OK)

   content = json.loads(response.content)
   self.assertIn('access', content)
   self.assertIn('refresh', content)
   
def test_authorization(self):
   auth_url = '/web-api/token/'
   response = self.client.post(auth_url, user_info, format='json')
   access_token = json.loads(response.content)['access']

   verification_url = '/web-api/recite/'

   client = APIClient()
   client.credentials(HTTP_AUTHORIZATION=f'Bearer {access_token}')
   response = client.get(verification_url)

   content = json.loads(response.content)
   self.assertEqual(content['code'], status.HTTP_200_OK)

在接口中實現登錄(返回Token)

先定義一個JWTTokenObtainPairSerializer,繼承自TokenObtainPairSerializer,實現get_token方法

# serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class JWTTokenObtainPairSerializer(TokenObtainPairSerializer):

   @classmethod
   def get_token(cls, user):
       token = super(JWTTokenObtainPairSerializer, cls).get_token(user)
       token['username'] = 'wx_{0}'.format(user.username)
       return token
在小程序登錄的接口添加如下代碼即可將token返回



# viewset.py
user = update_or_create_wx_user(openid, user_info)  # noqa
token = JWTTokenObtainPairSerializer.get_token(user).access_token
serializer = self.get_serializer(user)

result = {
   'userInfo': serializer.data,
   'token': str(token),
}
res = {
   'code': 200,
   'result': result,
}

return Response(res)

小程序端獲取到token后,塞入header即可實現賬號的登錄認證。Django會根據token自動獲取user。

以上就是“django框架開發小程序如何處理認證問題(django框架實戰開發小程序)”的詳細內容,想要了解更多django框架內容歡迎持續關注編程學習


掃碼二維碼 獲取免費視頻學習資料

Python編程學習

查 看2022高級編程視頻教程免費獲取