Django JWT token 登录注册
标签搜索
侧边栏壁纸
博主昵称
2c

  • 累计撰写 19 篇文章
  • 累计收到 12 条评论

Django JWT token 登录注册

2c
2c
2022-04-28 / 0 评论 / 14 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年05月23日,已超过496天没有更新,若内容或图片失效,请留言反馈。

setting.py

  INSTALLED_APPS = [
  ...
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',  # 添加 django-cors-headers 使其可以进行 cors 跨域
    'app01',
...
]
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL=True

# jwt载荷中的有效期设置
JWT_AUTH = {
    # 1.token前缀:headers中 Authorization 值的前缀
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    # 2.token有效期:一天有效
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
    # 3.刷新token:允许使用旧的token换新token,接口对接需要设置为true
    'JWT_ALLOW_REFRESH': True,
    # 4.token有效期:token在24小时内过期, 可续期token
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24),
    # 5.自定义JWT载荷信息:自定义返回格式,需要手工创建
    'JWT_RESPONSE_PAYLOAD_HANDLER': 'app01.views.jwt_response_payload_handler',
}
# AUTHENTICATION_BACKENDS = ['user.utils.EmailAuthBackend']
# 在DRF配置文件中开启认证和权限
REST_FRAMEWORK = {

    # 用户登陆认证方式
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',    # 在DRF中配置JWT认证
        # 'rest_framework.authentication.SessionAuthentication',  # 使用session时的认证器
        # 'rest_framework.authentication.BasicAuthentication'     # 提交表单时的认证器
    ],
    # 权限配置, 顺序靠上的严格
    'DEFAULT_PERMISSION_CLASSES': [
        # 'rest_framework.permissions.IsAdminUser',                # 管理员可以访问
        'rest_framework.permissions.IsAuthenticated',              # 全局配置只有认证用户可以访问接口
        # 'rest_framework.permissions.IsAuthenticatedOrReadOnly',  # 认证用户可以访问, 否则只能读取
        # 'rest_framework.permissions.AllowAny',                   # 所有用户都可以访问
    ],

}

urls.py

from django.urls import include, path
from rest_framework.authtoken.views import obtain_auth_token

from app01 import views
from rest_framework_jwt.views import obtain_jwt_token
from django.contrib import admin
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', obtain_jwt_token),  # 登录url,用于获取token
    path('register/', views.RegisterView.as_view()),  # 注册视图,  /user/register/
    path('adduser/',views.adduserList.as_view()),
    path('getuserlist/', views.getuserlist.as_view()),

]

views.py

from rest_framework.permissions import AllowAny

from .models import *
from .ser import seruserlist,sergetuserList
from django.contrib.auth.backends import ModelBackend
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username,
        "code": 200,
        "state": True
    }


class RegisterView(APIView):
    """
    用户注册, 权限是: 匿名用户可访问
    """
    # 自定义权限类
    permission_classes = (AllowAny,)

    def post(self, request):
        """
        接收邮箱和密码, 前端校验两遍一致性, 注册成功后返回成功, 然后用户自行登录获取token
        1. 随机用户名
        2. 生成用户
        3. 设置用户密码
        4. 保存用户
        :param request:
        :return:  {'code':0,'msg':'注册成功'}
        """
        email = request.data.get('email')
        passwrod = request.data.get('password')
        username = request.data.get('username')

        if all([email, passwrod]):
            pass
        else:
            return Response({'code': 9999, 'msg': '参数不全'})
        user = User(username=username, email=email)
        user.set_password(passwrod)  # 密码加密
        user.save()
        return Response({'code': 0, 'msg': '注册成功'})


# 用户添加
class adduserList(APIView):
    # 自定义权限类

    def post(self, request):
        ser=seruserlist(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"msg": '成功',"code":200})

        return Response(data=ser.errors,status=400)





# 分页(局部):自定义分页器 局部
class PageNum(PageNumberPagination):
    # 查询字符串中代表每页返回数据数量的参数名, 默认值: None
    page_size_query_param = 'page_size'
    # 查询字符串中代表页码的参数名, 有默认值: page
    page_query_param = 'page'
    # 一页中最多的结果条数
    # max_page_size = 2
# 查询用户
class getuserlist(APIView):
    def get(self, request):
        queryset = userlist.objects.all()
        print(request)
        if request.GET.get('page'):
            print(queryset)
            # 分页
            pg = PageNum()
            page_objs = pg.paginate_queryset(queryset=queryset, request=request, view=self)
            ser = sergetuserList(instance=page_objs, many=True)  # 关联数据多条
            return Response(ser.data)
        ser = sergetuserList(instance=queryset, many=True)  # 关联数据多条
        return Response(ser.data)
0

评论 (0)

取消