如何使用 Django 的 JWT 身份验证进行注销?

问题描述 投票:0回答:2

我已将 DRF 和简单的 JWT 用于用户应用程序,并且我已尝试在 DRF 上注销应用程序,但我知道如何删除身份验证令牌,我有黑名单令牌,但令牌继续提供服务

我想删除身份验证令牌,因为刷新令牌现在在黑名单令牌中

authentication django-rest-framework jwt access-token logout
2个回答
0
投票

您需要将此设置放在settings.py中或在views.py中本地应用,如下所示

此设置适用于您全局应用的情况
JWT Auth

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

0
投票

**首先,您添加此应用程序 simpleJWT SimpleJWT 并将其列入黑名单,然后运行“python manage.py migrate”**。它将生成两个新表并管理列入黑名单的刷新令牌。

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",

    # installed apps
    "rest_framework",
    "rest_framework_simplejwt.token_blacklist",
]

刷新令牌需要设置在黑名单中。这样,任何人都无法访问之前的令牌。

 @api_view(['POST'])
    @permission_classes([IsAuthenticated])
    @authentication_classes([JWTAuthentication])
    def logout(request):
        """
        Log out all user.
        Args:
            request (HttpRequest): The client's request to the server.
        Returns:
            HttpResponseRedirect: Redirects the user to the Login page.
        """
        if request.method == 'POST':
            # Access the refresh token from request headers or cookies
            try:
                refresh_token = request.data["refresh"]
                #refresh_token = request.META.get('HTTP_AUTHORIZATION', '').split()[1]
                token = RefreshToken(refresh_token)
                token.blacklist()
                return Response({'message':'User logout successfully'},status=status.HTTP_205_RESET_CONTENT)
            except (ObjectDoesNotExist, TokenError) as err:
                return Response({'message':str(err)},status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'error': 'Invalid request method.'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
© www.soinside.com 2019 - 2024. All rights reserved.