簡體   English   中英

使用 python-social-auth 和 django-rest-framework 進行 JWT 身份驗證

[英]JWT auth using python-social-auth and django-rest-framework

我正在嘗試轉換我找到的一段代碼(使用python-social-auth )以使其處理 JWT 身份驗證而不是簡單的令牌身份驗證。

這是代碼:

@api_view(http_method_names=['POST'])
@permission_classes([AllowAny])
@psa()
def oauth_exchange_token_view(request, backend):
    serializer = SocialAccessTokenSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        # set up non-field errors key
        try:
            nfe = "non_field_errors"
        except AttributeError:
            nfe = 'non_field_errors'

        try:
            # this line, plus the psa decorator above, are all that's necessary to
            # get and populate a user object for any properly enabled/configured backend
            # which python-social-auth can handle.
            user = request.backend.do_auth(serializer.validated_data['access_token'])
        except HTTPError as e:
            # An HTTPError bubbled up from the request to the social auth provider.
            # This happens, at least in Google's case, every time you send a malformed
            # or incorrect access key.
            return Response(
                {'errors': {
                    'token': 'Invalid token',
                    'detail': str(e),
                }},
                status=status.HTTP_400_BAD_REQUEST,
            )

        if user:
            if user.is_active:
                token, _ = Token.objects.get_or_create(user=user)
                return Response({'access': token.key})
            else:
                return Response(
                    {'errors': {nfe: 'This user account is inactive'}},
                    status=status.HTTP_400_BAD_REQUEST,
                )
        else:
            return Response(
                {'errors': {nfe: "Authentication Failed"}},
                status=status.HTTP_400_BAD_REQUEST,

如您在上面的代碼中所見,令牌返回如下:

token, _ = Token.objects.get_or_create(user=user)
return Response({'access': token.key})

但我希望它使用djangorestframework-simplejwt返回一個 JWT。

終於找到了解決辦法:

from rest_framework_simplejwt.tokens import RefreshToken
# ...

@api_view(http_method_names=['POST'])
@permission_classes([AllowAny])
def register_view(request):
    # ...
        if user:
            if user.is_active:
                refresh = RefreshToken.for_user(user)
                res = {
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                }
                return Response(res)
        # ...

您無需為 simplejwt 編寫視圖。 只需在文檔中逐步進行。 對於大多數用例,simplejwt 的“入門”配置就足夠了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM