JWT(JSON Web Token)是一种用于身份验证和授权的安全传输格式,它可以在前后端分离的应用程序中实现用户身份认证和授权。

在Django中,我们可以使用第三方库django-rest-framework-jwt来实现JWT的认证和授权。以下是在Django中实现JWT认证和授权的步骤:

  1. 安装django-rest-framework-jwt库:
pip install djangorestframework-jwt
  1. 在Django的settings.py文件中配置JWT相关配置:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_ENCODE_HANDLER':
    'rest_framework_jwt.utils.jwt_encode_handler',

    'JWT_DECODE_HANDLER':
    'rest_framework_jwt.utils.jwt_decode_handler',

    'JWT_PAYLOAD_HANDLER':
    'rest_framework_jwt.utils.jwt_payload_handler',

    'JWT_SECRET_KEY': SECRET_KEY,

    'JWT_ALGORITHM': 'HS256',

    'JWT_VERIFY': True,

    'JWT_VERIFY_EXPIRATION': True,

    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),

    'JWT_ALLOW_REFRESH': True,

    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=30),

    'JWT_AUTH_HEADER_PREFIX': 'Bearer',
}
  1. 在Django的urls.py文件中定义JWT认证和授权的URL:
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token

urlpatterns = [
    path('api-token-auth/', obtain_jwt_token),
    path('api-token-refresh/', refresh_jwt_token),
    path('api-token-verify/', verify_jwt_token),
]
  1. 在前端中进行JWT认证和授权:

在前端中,我们可以使用axios库来发送HTTP请求并在请求头中添加JWT token。以下是一个例子:

import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 1000,
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('token')
  }
});

// 发送API请求
instance.get('/api/user/')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

在上面的例子中,我们通过localStorage.getItem('token')获取JWT token并将其添加到请求头中。

需要注意的是,JWT token的有效期是有限的,当token过期后,我们需要重新获取token或者使用刷新token来更新token。在Django中,我们可以通过发送POST请求到/api-token-refresh/来刷新token,以下是一个例子:

import axios from 'axios';

const instance = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 1000,
  headers: {
    'Authorization': 'Bearer ' + localStorage.getItem('token')
  }
});

// 刷新token
instance.post('/api-token-refresh/')
  .then(response => {
    localStorage.setItem('token', response.data.token);
  })
  .catch(error => {
    console.log(error);
  });

在上面的例子中,我们发送POST请求到/api-token-refresh/来刷新token,并将新的token存储到localStorage

python django 如何实现jwt前后端分离 代码实现及流程 详细一点

原文地址: https://www.cveoy.top/t/topic/fgeb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录