DRF使用JWT实现用户登录之django-rest-framework-jwt

在使用DRF前后端开发中,用户登录实现方法很多,本文说明使用django-rest-framework-jwt
备注:django-rest-framework-jwt 此方式作者已停止维护,详见github

版本

Django 2.2.3
Python 3.8.8
djangorestframework 3.13.1

目标效果

什么是JWT

(引自官网翻译)JSON Web Token是一种开放的行业标准 ‎‎RFC7519‎‎ 方法,用于在双方之间安全地表示声明。

新建项目及应用

项目目录结构

项目配置settings.py

import os
import sys

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(BASE_DIR, "apps"))

...

INSTALLED_APPS = [
    ...
    'rest_framework',
    'users',
]

...
STATIC_URL = '/static/'

# 指定用户模型
AUTH_USER_MODEL = "users.User"

# JWT
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

项目路由配置urls.py

from django.contrib import admin
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-token-auth/', obtain_jwt_token),
]

apps/users/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser


# Create your models here.
class User(AbstractUser):
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")

    class Meta:
        db_table = "drf_users"
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

创建数据库表

>>> python manage.py makemigrations
>>> python manage.py migrate

创建用户

>>> python manage.py createsuperuser
admin
April@1234

启动项目

>>> python manage.py runserver 8000

postman验证

总结

这只是简单使用,更多方法参见项目文档
https://jpadilla.github.io/django-rest-framework-jwt/#verify-token

posted @   不吃浅水鱼  阅读(362)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示