JWT-авторизация с использованием python-social-auth и 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})
Но я бы хотел, чтобы он возвращал JWT, используя djangorestframework-simplejwt вместо этого.
Наконец-то найдено решение:
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.