reactjsdjangodjango-rest-frameworkaxiosdjango-rest-framework-simplejwt

axiosInstance raise error ->( Invalid token specified) -> after update -> user profile information ? why ? please solve it


in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE and PyCharm Community Edition 2023.2 and djangorestframework==3.14.0 and Django==4.2.4 and djangorestframework-simplejwt==5.3.0.

  1. FRONTEND

Consider - axiosInstance.js:

import jwt_decode from 'jwt-decode';
import dayjs from 'dayjs';
import axios from 'axios';
import { AxiosRequestConfig } from 'axios';
import {updateAccessToken} from '../actions/userActions';
const baseURL = 'http://127.0.0.1:8000';

export const axiosInstance = (userInfo , dispatch) => {

    const instance = axios.create({

        baseURL : baseURL,
        headers :  {
            'Content-Type': 'application/json',
            Authorization:`Bearer ${userInfo?.access}`,
        }
    });


    instance.interceptors.request.use(async (req)=> {

            const user = jwt_decode(userInfo.access);
            const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
            if (!(isExpired)) {
                return req
            }

            const response = await axios.post(
                '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh},
            );


            dispatch(updateAccessToken(response.data))
            req.headers.Authorization = `Bearer ${response.data.access}`;
            return req;

    });
    return instance
}

Consider - userActions.js - updateUserProfileAction :

export const updateUserProfileAction = (user) => async (dispatch, getState) => {
    try {
        dispatch({ // USER UPDATE PROFILE REQUEST
            type: USER_UPDATE_PROFILE_REQUEST,
        });
        const {userLogin: {userInfo}} = getState(); //GET STATE FROM STORE BY KEY `USER_LOGIN`
        
        const authRequestAxios = axiosInstance(userInfo,dispatch)
        const {data} = await authRequestAxios.put('http://127.0.0.1:8000/api/v1/users/profile/update/', user)

        dispatch({ // USER UPDATE PROFILE SUCCESS
            type: USER_UPDATE_PROFILE_SUCCESS, payload: data,

        });

        dispatch({ //USER LOGIN SUCCESS
            type: USER_LOGIN_SUCCESS, payload: data,

        });
        localStorage.setItem('userInfo', JSON.stringify(data));

    } catch (error) {
        dispatch({ // USER UPDATE PROFILE FAILED
            type: USER_UPDATE_PROFILE_FAILED,
            payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
        });
    }
}

Consider - userActions.js - getUserDetailsAction :

export const  getUserDetailsAction = () => async (dispatch , getState) => {
    try {
        dispatch({
            type: USER_DETAILS_REQUEST
        });
        const {userLogin:{userInfo}} = getState();
        const authRequestAxios = axiosInstance(userInfo,dispatch)
        const {data} = await authRequestAxios.get(`/api/v1/users/${userInfo._id}/`);
        dispatch({
            type: USER_DETAILS_SUCCESS,
            payload: data,
        });
        localStorage.setItem('userDetails' , JSON.stringify(data));
    } catch (error) {
        dispatch({ // USER FURTHER INFORMATION FAILED
            type: USER_DETAILS_FAILED,
            payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
        });
    }
}

my problem -> axiosInstance after update user profile via action (arrow function) -> updateUserProfileAction show me at user details that working by action (arrow function) -> getUserDetailsAction by raise error Invalid token specified in screen of profile_screen.js , please help me solve it ? i guess error is on axiosInstance in axiosInstance.js -> please solve it ... if you want more details , i can edit for adding more code from my application , thanks very lot.

  1. BACKEND

Consider - settings.py:

section 1:

#### --------------------------- OUR SETTINGS ---------------------------------####
# settings for allowed origins (https://example.com:port)

CORS_ALLOWED_ORIGINS = [

    "http://localhost:3000",
    "http://127.0.0.1:3000",
]

CORS_ALLOW_METHODS = (
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
)

CORS_ALLOW_HEADERS = (
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
)

CSRF_TRUSTED_ORIGINS = [
    "http://localhost:3000/",
    "http://27.0.0.1:3000/",
]

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    # 'DEFAULT_PERMISSION_CLASSES' : [
    #     'rest_framework.permissions.IsAuthenticated' ,
    # ]

    'DEFAULT_RENDERER_CLASSES': [
        # 'rest_framework_yaml.renderers.YAMLRenderer',
        'rest_framework.renderers.JSONRenderer',
        # 'rest_framework.renderers.AdminRenderer',
        # 'rest_framework.renderers.BrowsableAPIRenderer',
    ],
}

# Django project settings.py (JWT_SYSTEM_SETTINGS)

from datetime import timedelta

SIMPLE_JWT = {
    "ACCESS_TOKEN_LIFETIME": timedelta(minutes=10),
    "REFRESH_TOKEN_LIFETIME": timedelta(days=30),
    "ROTATE_REFRESH_TOKENS": True,
    "BLACKLIST_AFTER_ROTATION": True,
    "UPDATE_LAST_LOGIN": False,

    "ALGORITHM": "HS256",
    "SIGNING_KEY": SECRET_KEY,
    "VERIFYING_KEY": "",
    "AUDIENCE": None,
    "ISSUER": None,
    "JSON_ENCODER": None,
    "JWK_URL": None,
    "LEEWAY": 0,

    "AUTH_HEADER_TYPES": ("Bearer",),
    "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION",
    "USER_ID_FIELD": "id",
    "USER_ID_CLAIM": "user_id",
    "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule",

    "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",),
    "TOKEN_TYPE_CLAIM": "token_type",
    "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser",

    "JTI_CLAIM": "jti",

    "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp",
    "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5),
    "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1),

    "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer",
    "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer",
    "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer",
    "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer",
    "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer",
    "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
}

section 2:

from pathlib import Path

import os, sys

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my secret key'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    # my apps
    'base.apps.BaseConfig',
    'rest_framework',
    'corsheaders',
    'security',
    'rest_framework_simplejwt',
    'rest_framework_simplejwt.token_blacklist',
    # 'rest_framework_simplejwt.token_blacklistauthentication',
    'chat',
    'channels',
    # default apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # django-security middleWare
    'security.middleware.DoNotTrackMiddleware',
    'security.middleware.ContentNoSniff',
    'security.middleware.XssProtectMiddleware',
    'security.middleware.XFrameOptionsMiddleware',
    # cors-headers middleWare
    "corsheaders.middleware.CorsMiddleware",
]

ROOT_URLCONF = 'backend.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'
# ASGI_APPLICATION = 'backend.asgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
# for deploy by run `python manage.py collectstatic` in terminal or cmd in virtual enviroment (example : venv folder)

STATIC_URL = 'static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'statics/')
MEDIA_URL = 'images/'
MEDIA_ROOT = 'static/images/'
STATICFILES_DIRS = [
    BASE_DIR / 'static'
]

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

Consider - user_views.js:

section 1:

@api_view(http_method_names=['GET'])
@permission_classes([IsAuthenticated])
def get_user(request, user_id):
    CustomUser = get_user_model()

    user = CustomUser.objects.filter(id=user_id).first()
    if request and hasattr(request, "META"):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    else:
        x_forwarded_for = False
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    user_ip = ip

    user.user_ip = user_ip
    user.save()
    srz_data = UserSerializerWithToken(instance=user, many=False)

    return Response(data=srz_data.data)
 

section 2:

@api_view(http_method_names=['PUT'])
@permission_classes([IsAuthenticated])
def update_profile(request):
    CustomUser = get_user_model()
    visitor_user = request.user
    try:
        data = request.data
        user = CustomUser.objects.filter(id=data['id']).first()
        if user != visitor_user:
            return Response({"Permission denied": "you are not the owner"}, status=status.HTTP_401_UNAUTHORIZED)
        user.first_name = data['name']
        user.last_name = data['family']
        user.email = data['email']
        user.username = data['email']
        if request and hasattr(request, "META"):
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            x_forwarded_for = False
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        user_ip = ip
        user.user_ip = user_ip
        if data['password'] != "":
            user.password = make_password(data['password'])
        user.save()
        serializer = UserSerializerWithToken(instance=user, many=False, partial=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
        # email_exists = CustomUser.objects.filter(email=data['email']).first()
        # if email_exists is None:
        #     user.save()
        #     serializer = UserSerializerWithToken(instance=user, many=False, partial=True)
        #     return Response(serializer.data, status=status.HTTP_201_CREATED)
        # return Response({"detail": "user with email already exists"}, status=status.HTTP_400_BAD_REQUEST)
    except APIException as err:
        message = {'detail': str(err)}
        return Response(str(err), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

i had errors at run python manage.py migrate for migrating -> 'rest_framework_simplejwt.token_blacklist' but solve it automatic after seconds and i went codes right , but give me common error (Invalid token specified) at FRONTEND , please help me solve... and i don't take statment:

try:
       pass

except APIException as err:
       pass

in functional view def get_user(request, user_id): at user_views.py whom with api connect to FRONTEND by reactjs at arrow function -> getUserDetailsAction that it give me same error (Invalid token specified) in screen after update user profile that updating implementing by action (react-redux) ->arrow function -> userFurtherInformationAction and this action by arrow function is connecting by api (djangorestapi) to def update_profile(request): in BACKEND by django ... if you more details i add again , only please response this my question (???)


Solution

  • I should change userInfo.access to userInfo.token:

    Consider axiosInstance.js:

    import jwt_decode from 'jwt-decode';
    import dayjs from 'dayjs';
    import axios from 'axios';
    import { AxiosRequestConfig } from 'axios';
    import {updateAccessToken} from '../actions/userActions';
    import {USER_DETAILS_RESET} from "../constants/userConstants";
    const baseURL = 'http://127.0.0.1:8000';
    
    export const axiosInstance = (userInfo , dispatch) => {
    
        const instance = axios.create({
    
            baseURL : baseURL,
            headers :  {
                'Content-Type': 'application/json',
                Authorization:`Bearer ${userInfo.access}`,
            }
        });
    
    
        instance.interceptors.request.use(async (req)=> {
    
                const user = jwt_decode(userInfo.token);
                const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
                if (!(isExpired)) {
    
                    return req
                }
    
                const response = await axios.post(
                    '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh},
                );
    
    
                dispatch(updateAccessToken(response.data))
                req.headers.Authorization = `Bearer ${response.data.access}`;
                return req;
    
        });
        return instance
    }
    

    In fact , I have Authorization:'Bearer ${userInfo.access}', whom it changing to empty sting after first request to server (backend) that implementing by django and django-rest-framework and django-rest-frame-work-simplejwt in this web application and jwt_decode() module only accept a validate jwt-token and for an empty string comeback same common error (Invalid token specified) because , here token is empty and not validate so jwt_decode() module can not parse it well , and raise this error.

    Fortunately i have good implementing in django backend in serializers.py for this problem - Consider:

    section 1:

    class UserSerializer(serializers.ModelSerializer):
        name = serializers.SerializerMethodField(read_only=True)
        family = serializers.SerializerMethodField(read_only=True)
        _id = serializers.SerializerMethodField(read_only=True)
        isAdmin = serializers.SerializerMethodField(read_only=True)
        sex = serializers.SerializerMethodField(read_only=True)
        userPicture = serializers.SerializerMethodField(read_only=True)
        userIp = serializers.SerializerMethodField(read_only=True)
        userInfo = serializers.SerializerMethodField(read_only=True)
        userActive = serializers.SerializerMethodField(read_only=True)
    
    
    
        class Meta:
            model = get_user_model()
            # fields = "__all__"
            fields = ['_id', 'name', "family", 'email', 'sex', 'userIp', 'userInfo', 'userActive', 'userPicture', 'isAdmin' , 'password']
            extra_kwargs = {
                'password': {"write_only": True, },
                # "email": {"validators": (clean_email,), },
    
            }
    
        # def validate_email(self, value):
        #     if not User.objects.filter(email__iexact=value).exists():
        #         raise serializers.ValidationError("email is not correct !")
        #     return value
        #
        # def validate_password(self, value):
        #     if not User.objects.filter(password__iexact=value).exists():
        #         raise serializers.ValidationError("password is not correct !")
        #     return value
        def get_name(self, obj):
            name = obj.first_name
            return name
    
        def get_sex(self, obj):
            sex = obj.gender
            return sex
    
        def get_userIp(self, obj):
            userIp = obj.user_ip
            return userIp
    
        def get_userPicture(self, obj):
            # userPicture = obj.profile_image
            # return userPicture
    
            if obj.profile_image and hasattr(obj.profile_image, 'url'):
                print(obj.profile_image.url)
    
                userPicture = obj.profile_image.url
                return userPicture
    
        def get_family(self, obj):
            family = obj.last_name
            return family
    
        def get__id(self, obj):
            _id = obj.id
            return _id
    
        def get_isAdmin(self, obj):
            isAdmin = obj.is_staff
    
            return isAdmin
        def get_userActive(self , obj):
            userActive = obj.is_active
            return userActive
        def get_userInfo(self, obj):
    
            try:
                response = requests.get('https://api64.ipify.org?format=json', timeout=1000).json()
            except:
                response = None
            if response is None:
                user_ip = None
            else:
                user_ip = response['ip']
    
            try:
                userInfo = requests.get(f'https://ipapi.co/{user_ip}/json/', timeout=1000).json()
            except:
                userInfo = None
            # obj.user_info = userInfo
            # obj.save()
            # userInfo = obj.user_info
            if userInfo is None:
                userInfo = {}
    
            return userInfo
    

    in section 1 i programming class -> class UserSerializer(serializers.ModelSerializer): as active user of this web application but this system in simplejwt (for django) once generate jwt_token in login and after first login access and refresh token do not generate jwt so i programming section 2 that it is a class -> UserSerializerWithToken(UserSerializer): whom this class inheritance parent class in section 1 and has special method -> def get_token(self, obj): - Consider:

     def get_token(self, obj):
                token = RefreshToken.for_user(obj)
        
                return str(token.access_token)
    

    this method generate access token in every request so Authorization:'Bearer ${userInfo.token}', is not empty and jwt_decode() parsing it well and right.

    section 2:

    # validating by validators in #### https://www.django-rest-framework.org/api-guide/serializers/#validation ####
    
    class UserSerializerWithToken(UserSerializer):
        token = serializers.SerializerMethodField(read_only=True)
    
        class Meta:
            model = get_user_model()
            fields = ['_id', 'name', 'family', 'email', 'sex', 'userPicture', 'userActive', 'userIp', 'userInfo', 'isAdmin', 'token' , 'password']
            # fields = "__all__"
    
        def get_token(self, obj):
            token = RefreshToken.for_user(obj)
    
            return str(token.access_token)
    

    more information -> i have bugs in my code because in method -> def get_token(self, obj): i get access token only , but i should get refresh token , too -> so: Consider:

     def get_token(self, obj):
                token = RefreshToken.for_user(obj)
        
                return str(token.access_token)
    

    instead to:

    def get_token(self, obj):
               token = RefreshToken.for_user(obj)
               return str(token.access_token)
    
    def get_refreshToken(self,obj)
               token = RefreshToken.for_user(obj)
               return str(token)
    

    and add refreshToken = serializers.SerializerMethodField(read_only=True) to class UserSerializerWithToken(UserSerializer): to complete this part of code , too,

    and i should compatible my app with this refershToken and token instead refresh and access that simplejwt generate once after login user and send it to redux of react in FRONTEND -> solve it => i should change userInfo.access to userInfo.token and change userInfo.refresh to userInfo.refreshToken in axiosInstance.js.

    Consider axiosInstance.js (changed):

    import jwt_decode from 'jwt-decode';
    import dayjs from 'dayjs';
    import axios from 'axios';
    import { AxiosRequestConfig } from 'axios';
    import {updateAccessToken} from '../actions/userActions';
     
     
    export const axiosInstance = (userInfo , dispatch) => {
        const baseURL = 'http://127.0.0.1:8000';
    
    
        const instance = axios.create({
    
            baseURL : baseURL,
            headers :  {
                'Content-Type': 'application/json',
                Authorization:`Bearer ${userInfo?.token}`,
            }
        });
    
    
        instance.interceptors.request.use(async (req)=> {
    
                const user = jwt_decode(userInfo.token);
                const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
                if (!(isExpired)) {
    
                    return req
                }
    
                const response = await axios.post(
                    'http://127.0.0.1:8000/api/v1/users/token/refresh/' , {refresh:**userInfo.refreshToken**},
                );
    
    
                dispatch(updateAccessToken(response.data))
                req.headers.Authorization = `Bearer ${response.data.access}`;
                return req;
    
        });
        return instance
    }
    

    so in updateAccessToken() that is imported and dispatched by dispatch() (method of react-redux) on axiosInstance.js i assigned userInfo.access to userInfo.token and userInfo.refresh to userInfo.refreshToken , because access and refresh generate once after request 'http://127.0.0.1:8000/api/v1/users/token/refresh/' and next time remove from redux but token and refreshToken that handle by coder whom these tokens are not removed after request and i use it and never raise error -> (Invalid token specified) .

    userActions.js - updateAccessToken (arrow function - action (react-redux)):

    export const updateAccessToken = (obj) => (dispatch , getState) => {
        const {userLogin:{userInfo}} = getState();
        userInfo.token = obj.access;
        userInfo.refreshToken = obj.refresh;
    
    
    
        dispatch({type: USER_LOGIN_SUCCESS , payload: userInfo});
    
        localStorage.setItem('userInfo' ,JSON.stringify(userInfo));