欢迎访问宙启技术站
智能推送

rest_framework.permissions中的Token认证和Session认证

发布时间:2023-12-24 04:01:54

在Django Rest Framework(DRF)中,我们可以使用TokenAuthenticationSessionAuthentication来实现Token认证和Session认证。这两种认证机制可以用于保护DRF API视图类的访问权限。

首先,我们需要进行设置,以便支持这两种认证方式。在settings.py文件中添加以下代码:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
}

这会将TokenAuthenticationSessionAuthentication作为默认的认证类。

接下来,让我们看看如何在视图类中使用这两种认证方式。

1. Token 认证

- 创建一个名为TokenView的API视图类,继承自DRF的APIView

from rest_framework.views import APIView
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response


class TokenView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        username = request.user.username
        return Response({"message": f"Hello, {username}! You are authenticated using Token."})

在上述代码中,我们使用TokenAuthentication来设置认证类,并使用IsAuthenticated来设置权限类。这意味着只有经过认证的用户才能访问该视图类。

2. Session 认证

- 创建一个名为SessionView的API视图类,继承自DRF的APIView

from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response


class SessionView(APIView):
    authentication_classes = [SessionAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        username = request.user.username
        return Response({"message": f"Hello, {username}! You are authenticated using Session."})

在上述代码中,我们使用SessionAuthentication来设置认证类,并使用IsAuthenticated来设置权限类。同样,只有经过认证的用户才能访问该视图类。

3. 测试 Token 认证

- 执行以下命令来创建一个token:

python manage.py drf_create_token <username> # 替换为实际的用户名

- 使用创建的 token 在请求头中进行身份验证。

GET /api/token/ HTTP/1.1
Host: localhost:8000
Authorization: Token <token> # 替换为实际的 token 值

如果认证成功,您将收到以下响应:

HTTP/1.1 200 OK
Content-Type: application/json

{
    "message": "Hello, <username>! You are authenticated using Token."
}

4. 测试 Session 认证

- 使用浏览器访问以下URL来启动会话:

GET /api-auth/login/

- 使用正确的用户名和密码进行登录。

- 访问受保护的视图类的URL:

GET /api/session/ HTTP/1.1
Host: localhost:8000

如果认证成功,您将收到以下响应:

HTTP/1.1 200 OK
Content-Type: application/json

{
    "message": "Hello, <username>! You are authenticated using Session."
}

以上是使用TokenAuthenticationSessionAuthentication进行认证的例子。这两种认证方式在DRF中非常常用,您可以根据自己的需求选择适合您的API的认证方式。