django用户认证

基础token认证

因为session的认证方式有一些问题,所以采用token认证的方式,通过账号密码认证后会返回一个token,之后浏览器每次请求都携带这个token. 有则表示登录过了,无则需要重新登录。
DRF提供了一个TokenAuthentication,但是这种方式需要数据库存储token, 所以采用互联网比较流行的做法jwt(JSON Web Token)也是较好的选择,并且DRF也提供了第三方插件。
JWT官网 https://jwt.io/
官网 https://github.com/jazzband/djangorestframework-simplejwt
文档 https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html
要求:Python 3.7+、Django 2.2+、DRF 3.10+

安装

pip install djangorestframework-simplejwt

setting.py中添加配置

INSTALLED_APPS = [
,,,,,,,,,
    'djangorestframework-simplejwt'
]


REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework_simplejwt.authentication.JWTAuthentication',
]}

主路由配置 urls.py

from django.urls import path,include
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshSlidingView
)
tobview=TokenObtainPairView.as_view()
urlpatterns = [
    path('login/', tobview),
    path('token/', tobview),
    path('token/refresh', TokenRefreshSlidingView.as_view()),
]

TokenObtainPairView的父类TokenViewBase继承自GenericAPIView,且只实现了post方法,所以只能使用POST请求。

请求测试

GET http://127.0.0.1:8000/token/

返回:400
{
    "code": 10000,
    "message": "非法请求"
}

POST http://127.0.0.1:8000/token/

{
    "username": [
        "这个字段是必填项。"
    ],
    "password": [
        "这个字段是必填项。"
    ]
}

必须提交账号密码到接口,认证成功则返回token,认证失败则返回401.
提交信息后,内部会查数据库和对比密码,认证成功就返回token信息,token 由userid,过期时间组成。


image.png

JWT分为3部分,头、数据、签名,中间那部分使用Base64解码可以得到

{"token_type":"access","exp":1628792597,"jti":"df76bb1f43344eb3959dc2fa0c93e1
61","user_id":1}

jti就是jwt的id,唯一标识。user_id就是认证成功后返回的用户id值。exp过期的时间点的时间戳,默认5分钟后。
refresh是access短时间token过期后,对access延期的。

token的过期时间设置 setting.py

from datetime import timedelta
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(hours=1),
     #'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}

登录测试

主路由添加user的二级路由

urlpatterns = [
-----------------
    path('users/',include("user.urls"))
]
image.png

编写登录视图

我是有个user 应用,我在user中的view.py中写

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.request import Request

@api_view(['POST', 'GET'])
def test(request:Request):
    print('~' * 30)
    print(request.COOKIES, request._request.headers)
    print(request.data) # 被DRF处理为字典
    print(request.user) # 可能是匿名用户
    print(request.auth)
    print('=' * 30)
    if request.auth:

        return Response({'test':10000})
    else:
        return Response({'test':20000})

编写二级路由 user/url.py

from django.urls import path
from .views import test
urlpatterns = [
 path('test/',test)
] 

不带token返回


image.png

image.png

带token返回


image.png

image.png

token就是在请求时添加到请求头上的,有token并且服务端验证成功则走成功流程,验证失败走失败流程。不带token DRF则获取不到请求用户,使用默认的AnonymousUser用户。


image.png

开启请求所有路由必须通过认证

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework_simplejwt.authentication.JWTAuthentication',
],
    'EXCEPTION_HANDLER': 'utils.exceptions.global_exception_handler',
    'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.IsAuthenticated'],
}

此时不提供token将无法访问


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容