1、JSON Web 令牌(JSON Web Token, JWT)是一个开放标准,它利用简洁且自包含的JSON对象形式安全传递信息。JWT的构成简单,且传输信息中已经包含用户信息,JWT由3个部分组成,分别是头部负载签名,三者之间以点号隔开,如图

2、照着书本代码敲完,想启动项目报错

 ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding'

后面参照这篇文章成功解决问题[注意看细节]。DRF 使用 simpleJWT登陆认证(一)基本使用入门_importerror: could not import ‘rest_framework_jwt._豌豆code的博客-CSDN博客

3、下面是自己项目相关部分代码:

     3.1配置信息

# settings.py 部分代码

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'web.apps.WebConfig',
    'RestFramework.apps.RestframeworkConfig',
    'rest_framework',
    'rest_framework_simplejwt'
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAdminUser',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.TokenAuthentication',
    )
}

SIMPLE_JWT = {
    # token有效时长(返回access 有效时长)
    'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=30),
    # token刷新的有效时间(返回refresh 有效时长)
    'REFRESH_TOKEN_LIFETIME': datetime.timedelta(seconds=20),
}

     3.2路由信息

# urls.py部分代码

from web.views import Login, task, hello_request, world_request
from web.views import DemoView
from RestFramework.views import DefectList
from RestFramework.views import DefectDetail
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView
from rest_framework import routers, serializers, viewsets
from django.contrib.auth.models import User


# Serializers define the API representation.

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')


# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    path("admin/", admin.site.urls),
    path('', include(router.urls)),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),
    path('defects/', DefectList.as_view()),  # 此接口的作用是返回缺陷表中的全部记录
    path('defect/<str:bug_code&gt;/', DefectDetail.as_view()),  # 此接口的作用是对某条缺陷记录进行修改删除
]

    3.3视图信息: 

# views.py 部分代码

from RestFramework.models import Defect
from RestFramework.serializers import DefectSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class DefectList(APIView):  # APIView 是RESTFramework提供的所有视图基类继承自Django的View父类def get(self, request):
        defects = Defect.objects.all()
        serializer = DefectSerializer(defects, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = DefectSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 用于完成单条记录请求处理
class DefectDetail(APIView):
    def get_object(self, request, bug_code):
        """
        由于后续代码需要反复获取一条缺陷记录,因此将该操作定义一个公共函数bug_code 参数代表需要提取的缺陷编号
        """
        try:
            return Defect.objects.get(bug_code=bug_code)  # 如果找到了传入缺陷编号对应数据记录,将其返回
        except Defect.DoesNotExist:
            raise Http404

    def get(self, request, bug_code):
        defect = self.get_object(self, bug_code)  # 返回缺陷编号对应一条缺陷记录对象
        serializer = DefectSerializer(defect)  # 对缺陷记录对象进行序列化
        return Response(serializer.data)  # 装饰序列化的JSON数据作为HTTP的响应内容返回

    def put(self, request, bug_code):
        defect = self.get_object(self, bug_code)  # 返回缺陷编号对应一条缺陷记录对象
        serializer = DefectSerializer(defect, data=request.data)  # 对缺陷数据进行序列化处理
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, bug_code):
        defect = self.get_object(self, bug_code)  # 返回缺陷编号对应一条缺陷记录对象
        defect.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)  # 代表内容(因为已经被删除了)

 4、验证

 5、Postman 模拟请求把鉴权信息传到下个接口

     5.1获取token信息     5.2把响应值设置全局变量以便其他接口请求拿到到access_token值

     5.3未授权前,请求提示权限

     5.4授权后,请求成功获取相关数据信息需要在请求头加上Authorization格式Bearer [token值] 有空格

JWT授权为啥要在 Authorization标头里加个Bearer 呢_authorization bearer_小白de成长之路的博客-CSDN博客

 jwt token为什么要在前面添加Bearer这个单词? – 简书

原文地址:https://blog.csdn.net/mohuisheng/article/details/129242426

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_25270.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注