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

如何使用TokenAuthentication()在Python中实现API令牌认证

发布时间:2024-01-01 14:51:13

在Python中,我们可以使用Django框架自带的TokenAuthentication类来实现API令牌认证。TokenAuthentication是基于Token的身份验证系统,它使用API令牌作为用户的凭据进行身份验证。

首先,我们需要在Django项目的settings.py文件中添加以下代码来启用TokenAuthentication:

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

接下来,我们需要创建一个Token模型和一个Token生成函数。可以在models.py文件中定义Token模型,如下所示:

from django.db import models
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string

class Token(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    token = models.CharField(max_length=40, unique=True)

    def save(self, *args, **kwargs):
        if not self.token:
            self.token = get_random_string(40)
        return super(Token, self).save(*args, **kwargs)

    def __str__(self):
        return self.token

接下来,在views.py文件中,我们可以使用TokenAuthentication类来保护需要进行令牌认证的API视图函数。以下是一个简单的示例:

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response

@api_view(['GET'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def example_view(request):
    return Response({"message": "Hello, authenticated user!"})

在上面的代码中,我们使用@api_view装饰器将函数指定为可以作为API视图使用的函数。然后,我们使用@authentication_classes装饰器将TokenAuthentication类添加到视图的身份验证类列表中。最后,我们使用@permission_classes装饰器将IsAuthenticated类添加到视图的权限类列表中,以确保只有已经通过身份验证的用户才能访问该视图。

我们还可以使用rest_framework.authtoken.views模块中的obtain_auth_token函数来生成和获取令牌。以下是一个示例:

from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    # ...
    path('api-token-auth/', obtain_auth_token, name='api_token_auth'),
]