'Django:authorization fails when getting data with the token

After registering user, when I login, I get access token, and after that I want to get the user details back, but I am unable to to so. In Login.js authentication works and I get back access and refresh token, then I want to send another get request using that token,in order to get user details, but it gives unauthorized error.

backend

views.py

import json
from multiprocessing import context
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from rest_framework.decorators import api_view,permission_classes,authentication_classes
from oyren.serializers import CustomUserSerializer
from oyren.models import NewUser
from rest_framework import permissions



@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])  #authorization fails
def get_user_details(request):
    data={
        'user':request.user.name ,
        'email':request.user.email
    }
    return  JsonResponse(data)


@api_view(['POST']) #register view
def register(request):
   print(request.data)
   serializer=CustomUserSerializer(data=request.data);
   if serializer.is_valid():
       instance=serializer.save();
       instance.set_password(request.data['password'])
       instance.save();
       print("serializer is valid")
       return HttpResponse("serializer is valid")
   else:
        print('serializer is not valid')
        print(serializer.errors)
        return HttpResponse("serializeris not valid") 

# Create your views here.

settings.py

INSTALLED_APPS = [
    'oyren',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK={
    'DEFAULT_PERMISSION_CLASSES':[
        'rest_framework.permissions.AllowAny'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES':[
        'rest_framework_simplejwt.authentication.JWTAuthentication'
    ]
}

SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(minutes=1),
    'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
    'ROTATE_REFRESH_TOKENS': False,
    'BLACKLIST_AFTER_ROTATION': False,
    'UPDATE_LAST_LOGIN': False,

    'ALGORITHM': 'HS256',
    'SIGNING_KEY': SECRET_KEY,
    'VERIFYING_KEY': None,
    'AUDIENCE': None,
    'ISSUER': 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=1),
    'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
}

urls.py

urlpatterns = [
  path('register/',register),
  path('get_access_token/',TokenObtainPairView.as_view()),
  path('get_refresh_token/',TokenRefreshView.as_view()),
  path('get_user_details/',get_user_details)

]

frontend

Login.js

import img from '../images/x7.png'
import register from '../images/register.png'
import logo from '../images/logo.png'
import {Link,Route,Routes }from 'react-router-dom'
import Style from '../styles/Login.module.css'
import BASE_URL from './axios'
import { useNavigate } from 'react-router'
import axios  from 'axios'
const Login = ()=>{
    const history = useNavigate();
    const handleSubmit=(e)=>{
        e.preventDefault();
        let  data={
            'email':e.target[0].value,
            'password':e.target[1].value
        }
        axios.post(`${BASE_URL}/get_access_token/`,data) 
        .then((res)=>{
            localStorage.setItem('access_token',res.data.access)
            localStorage.setItem('refresh_token',res.data.refresh) //access and refresh token successfully obtained and stored 
            history('/teacher_home_page')
            return res

        })
        .then((res)=>{
            let access_token=localStorage.getItem('access_token')  
            console.log(access_token)
            let config={
                headers:{
                    Authorization: "Bearer"+ " " +  access_token  
                  }
                 }
            axios.get(`${BASE_URL}/get_user_details/`,config)//trying to use that token to send another request,requesting user details
            .then((res)=>{
                console.log(res)
            })
        })
        .catch((res)=>{
            alert("USER CREDENTIALS DID NOT MATCH")
        })
    }
    return (
        <>
      <div className={Style.container}>
       <div className={Style.logoContainer}>
       <img className ={Style.logo} src={logo}></img>
       <img className={Style.background} src={register}></img>
       </div>
<div className={Style.inputContainer}>
    <p  className={Style.welcome}>
        WELCOME TO THE  <br />
        LEARNING  <br />
        PLATFORM!
    </p>
    <form onSubmit={handleSubmit} className={Style.form}>
        <input  placeholder="Email"/>
        <input  placeholder="Password"/>
        <button type='submit'>Log In</button>
        <div className={Style.links}>  
         <Link to={'/register_as_student'}>  <a>Register as student</a></Link>
         <Link to={'/register_as_teacher'}>  <a>Register as teachet</a></Link>
        </div> 
    </form>
</div>
      </div>
        </>
    )

}

export  default Login


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source