在使用Django REST framework想用JWT的人会发现django-rest-framework-jwt已经停止了更新版本,其对新版本的Django REST framework并不支持,在这推荐django-rest-framework-simplejwt支持django2到3版本python3.7到3.9
1.安装
pip install django-rest-framework-simplejwt
2.配置
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
2.1 URL配置
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'),
...
]
2.2用postman测试
3. 设置自定义返回值
在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()),
]