没有用户模型的Django基于令牌的身份验证

AI *_*hon 2 django django-authentication jwt django-rest-framework pyjwt

我正在使用基于 Django 令牌的身份验证。(JWT Token 由 AWS Cognito 等第三方服务生成,我们将仅验证签名和到期时间)。

这个 REST 应用程序将没有任何用户模型,使用 API 调用的人只需要通过 JWT 令牌进行身份验证。

class JSONWebTokenAuthentication(TokenAuthentication):
    def authenticate_credentials(self, jwtToken):
        try:
            payload = jwt.decode(jwtToken, secret_key,verify=True)
            # user = User.objects.get(username='root')
            user =  AnonymousUser()
        except (jwt.DecodeError, User.DoesNotExist):
            raise exceptions.AuthenticationFailed('Invalid token')
        except jwt.ExpiredSignatureError:
            raise exceptions.AuthenticationFailed('Token has expired')
        return (user, payload)
Run Code Online (Sandbox Code Playgroud)

在视图中:

@api_view(["POST"])
@authentication_classes((JSONWebTokenAuthentication,))
@permission_classes((AllowAny,))
Run Code Online (Sandbox Code Playgroud)

上述过程根本没有跟踪Token。有/没有令牌,API 调用正在工作。如果我进行以下两项更改,则它正在工作。

user = User.objects.get(username='root')
#user = AnonymousUser()
@permission_classes((IsAuthenticated,))
Run Code Online (Sandbox Code Playgroud)

一种方法是,在我的应用程序中至少有一个用户并引用该用户[此网络应用程序可能会在需要时扩展到任意数量的实例,因此必须自动插入具有相同“用户名”的同一用户。]。但是,我可以消除身份验证中的“用户”概念吗?

小智 5

Django REST 框架很大程度上假设请求是基于用户进行身份验证的,但它们确实提供了对身份验证匿名请求的支持。但它通过给予匿名用户一定的权限,从“验证(django)用户是否真实”的标准假设中脱颖而出。第一个案例的问题是带有“Allow Any”的权限装饰器。

我建议有一个虚拟 Django 用户。(它也不会阻止您扩展到任意数量的实例)。

使用

user = User.objects.get_or_create(username='whatever')[0]
Run Code Online (Sandbox Code Playgroud)

代替

user =  AnonymousUser()
Run Code Online (Sandbox Code Playgroud)

现在将权限装饰器更改为

@permission_classes((IsAuthenticated,))
Run Code Online (Sandbox Code Playgroud)

除非您设置密码,否则任何人都无法登录该用户,而且以该用户身份登录也不会授予您访问 API 调用的权限。访问 API 的唯一方法是发送有效的令牌。

希望这可以帮助。

  • 谢谢。它对我来说是一种解决方法。当我使用像 AWS cognito 这样的第三方工具时,我相信我们根本不应该关心 Django 用户模型。 (2认同)

Rod*_*aga 5

使用django-rest-framework-simplejwt您可以设置DEFAULT_AUTHENTICATION_CLASSES为使用JWTTokenUserAuthentication并且即使没有用户也只需验证令牌。


Dr *_*tan 5

有时你真的不需要用户,例如,服务器到服务器的通信。这是一个解决方案。

覆盖 AnonymousUser 的 is_authenticated 属性,您就可以开始了

from django.contrib.auth.models import AnonymousUser

class ServerUser(AnonymousUser):

    @property
    def is_authenticated(self):
        # Always return True. This is a way to tell if
        # the user has been authenticated in permissions
        return True
Run Code Online (Sandbox Code Playgroud)

只需在您的自定义身份验证中返回这种新类型的用户

class CustomServerAuthentication(authentication.BaseAuthentication):
    keyword = 'Token'

    def authenticate(self, request):
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None

        if len(auth) == 1:
            raise exceptions.AuthenticationFailed('Invalid token header. No credentials provided.')

        elif len(auth) > 2:
            raise exceptions.AuthenticationFailed('Invalid token header. Token string should not contain spaces.')

        token = auth[1].decode()

        if not (settings.CUSTOM_SERVER_AUTH_TOKEN == token):
            raise exceptions.AuthenticationFailed('You do not have permission to access this resource')

        user = ServerUser()

        return user, None
Run Code Online (Sandbox Code Playgroud)