-1

When using the @csrf_protect decorator in the view, I encountered the error "Forbidden (CSRF token missing or incorrect): /api/token/refresh/"

views.py

@api_view(['POST'])
@renderer_classes([CustomizeJSONRenderer])
@csrf_protect
def refresh_token_view(request):
    refresh_token = request.COOKIES.get('refreshtoken')
    # check valid refresh token
    if refresh_token is None:
       raise exceptions.AuthenticationFailed('Authentication credentials were not 
                                              provided, please login.')

    try:
        payload = jwt.decode(refresh_token, settings.REFRESH_TOKEN_SECRET, 
                             algorithms=['HS256'])
    except jwt.ExpiredSignatureError:
           raise exceptions.AuthenticationFailed('expired refresh token, please login 
                                                  again.')

    user = User.objects.filter(id=payload.get('user_id')).first()
    # check valid user
    if user is None:
       raise exceptions.AuthenticationFailed('user not found.')
       if not user.is_active:
           raise exceptions.AuthenticationFailed('user is inactive.')

    access_token = generate_access_token(user) # create new access token
    return Response({'access_token': access_token})
Vahid
  • 1
  • 1
  • As the error say, your POST request is missing the CSRF token. – JanMalte Jul 08 '22 at 14:36
  • You are mixing up different things. A CSRF token is usally not used on an API. To add authentication to your API, you are using some kind of token in the header usally. https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication – JanMalte Jul 08 '22 at 14:43

1 Answers1

0

just write {% csrf_token %} in your HTML template where you wants to use your django command.

wahid
  • 1
  • 2