标签:login sel hmac 路由 groups 版本 访问 blank pair
在使用Django REST framework想用JWT的人会发现django-rest-framework-jwt已经停止了更新版本,其对新版本的Django REST framework并不支持,在这推荐django-rest-framework-simplejwt支持django2到3版本python3.7到3.9
pip install django-rest-framework-simplejwt
REST_FRAMEWORK = {
‘DEFAULT_AUTHENTICATION_CLASSES‘: (
‘rest_framework_simplejwt.authentication.JWTAuthentication‘,
)
}
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
urlpatterns = [
...
# 认证令牌
path(‘api/token/‘, TokenObtainPairView.as_view(), name=‘token_obtain_pair‘),
# 刷新令牌
path(‘api/refresh/‘, TokenRefreshView.as_view(), name=‘token_refresh‘),
...
]
如果您希望允许API用户无需访问您的签名密钥即可验证HMAC签名的令牌,还可以包括一个简单JWT的路由
urlpatterns = [
...
path(‘api/token/verify/‘, TokenVerifyView.as_view(), name=‘token_verify‘),
...
]
在app的 views中创建
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data[‘refresh‘] = str(refresh)
data[‘access‘] = str(refresh.access_token)
# Add extra responses here
data[‘username‘] = self.user.username
data[‘groups‘] = self.user.groups.values_list(‘name‘, flat=True)
return data
class MyTokenObtainPairView(TokenObtainPairView):
serializer_class = MyTokenObtainPairSerializer
在url中配置
from .views import MyTokenObtainPairView
urlpatterns = [
path(r‘login2/‘, MyTokenObtainPairView.as_view()),
]
django-rest-framework-simplejwt
标签:login sel hmac 路由 groups 版本 访问 blank pair
原文地址:https://www.cnblogs.com/zdqc/p/14121682.html