一、 Token Authentication的应用
(1)首先注册应用: 'rest_framework.authtoken'
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
然后python manage.py migrate 进行迁移, 数据库中会生成authtoken_token表
(2)获取token的示例代码
from rest_framework.authtoken.models import Token
token = Token.objects.create(user=...)
print(token.key)
发送http请求的时候,只需要在请求头上加上
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
如果请求头中不想使用Authorization作为keyword, 继承rest_framework.authentication的 TokenAuthentication类
然后自定义类,重新赋值 keyword 变量 如下所示:
class HMAuthentication(TokenAuthentication):
"""
Simple token based authentication .
Clients should authenticate by passing the token key in the 'Authorization'
HTTP header, prepended with the string 'HM_Token '. For example:
Authorization: HM_Token 956e252a-513c-48c5-92dd-bfddc364e812
"""
keyword = 'HM_Token'
这样请求头上加的键值对就是:
Authorization: HM_Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
最后,需要给特定的接口视图指定认证类authentication_classes
authentication_classes = (SessionAuthentication, BasicAuthentication, HMAuthentication)
二、JSON Web Token Authentication (JWT)
(1)安装JWT 依赖包
pip install djangorestframework-jwt
(2)settings.py 中追加配置相关代码
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', #必须有
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
)
}
import datetime
JWT_AUTH = {
# 指定token的有效期
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
(3)url配置
from django.contrib import admin
from django.urls import path
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, verify_jwt_token
urlpatterns = [
path('admin/', admin.site.urls),
path('jwt-token-auth/', obtain_jwt_token),
path('jwt-token-verify/', verify_jwt_token),
path('jwt-token-refresh/', refresh_jwt_token),
]
(4)请求 jwt-token-auth 接口
用post方法提交
{
"username":"root",
"password":"root2222"
}
返回得到jwt
{
"token":"xxxx.xxxx.xxxx"
}
(5) 使用jwt
请求的时候, 在请求头上加上键值对即可
{
"Authorization":"JWT xxxx.xxxx.xxxx"
}
实际项目中需要对 获取 jwt 的视图进行修改, 因为实际项目的认证方式并没有那么简单
参考连接
https://www.django-rest-framework.org/api-guide/authentication/
本文详细介绍了Django Rest Framework中的两种主要身份验证方法:TokenAuthentication和JSONWebTokenAuthentication(JWT)。包括如何注册和配置应用,获取和使用token,以及JWT的安装、设置和请求流程。
529

被折叠的 条评论
为什么被折叠?



