restframework使用JWT验证

2020-02-05  本文已影响0人  瀚海银月

1 安装Django扩展库

pip install djangorestframework
pip install djangorestframework-jwt

2 新建用户model, 在app/models.py文件中,若修改,请确保from app.models import 可以成功

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

# Create your models here.

#userProfile继承AbstractUser分类,进行拓展
class UserProfile(AbstractUser):
    """
    用户类拓展
    """
    name = models.CharField(max_length=30, null=True, blank=True, verbose_name="姓名" )
    avatar = models.CharField(max_length=100, null=True, blank=True, verbose_name="头像")
    role = models.CharField(max_length=10, default="员工", verbose_name="角色")

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

    def __str__(self):
        return self.username

3 执行数据库迁移

python manage.py makemigrations app_name
python mange.py migrate app_name

4 settings.py设置

AUTH_USER_MODEL = "interface.UserProfile" # interface为app_name
#设置rest-framework的权限验证
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}
#设置JWT的过期时间,以及JWT的token开头字符串(验证协议)
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
}

5 设置用户登录url,在urls.py中设置

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

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

操作完以上5步骤即可整合JWT到框架中


使用Postman或其他工具测试Token

python manage.py createsuperuser

保证请求的header中包含了Authorization的token,其中token前要加JWT(手动空格)

上一篇下一篇

猜你喜欢

热点阅读