{"id":17811242,"url":"https://github.com/seankwarren/django-react-jwt-authentication","last_synced_at":"2025-04-19T16:42:33.400Z","repository":{"id":157450900,"uuid":"602748355","full_name":"seankwarren/Django-React-jwt-authentication","owner":"seankwarren","description":"A tutorial for user authentication between a django backend and react frontend using jwt","archived":false,"fork":false,"pushed_at":"2024-08-27T21:20:34.000Z","size":466,"stargazers_count":132,"open_issues_count":0,"forks_count":28,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-29T10:22:35.430Z","etag":null,"topics":["django","django-rest-framework","jwt-authentication","react","rest-api","tutorial-code"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/seankwarren.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-16T21:27:00.000Z","updated_at":"2025-03-05T16:09:48.000Z","dependencies_parsed_at":null,"dependency_job_id":"c1948ac5-8f63-4e40-bcf1-71520494866a","html_url":"https://github.com/seankwarren/Django-React-jwt-authentication","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seankwarren%2FDjango-React-jwt-authentication","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seankwarren%2FDjango-React-jwt-authentication/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seankwarren%2FDjango-React-jwt-authentication/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/seankwarren%2FDjango-React-jwt-authentication/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/seankwarren","download_url":"https://codeload.github.com/seankwarren/Django-React-jwt-authentication/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249740557,"owners_count":21318694,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","django-rest-framework","jwt-authentication","react","rest-api","tutorial-code"],"created_at":"2024-10-27T15:46:15.629Z","updated_at":"2025-04-19T16:42:33.382Z","avatar_url":"https://github.com/seankwarren.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003c!-- TOC start --\u003e\n# Table of contents\n- [Table of contents](#table-of-contents)\n- [Introduction](#introduction)\n  - [What is JWT?](#what-is-jwt)\n- [Backend](#backend)\n  - [Boilerplate Setup](#boilerplate-setup)\n  - [Creating a view and routing it](#creating-a-view-and-routing-it)\n  - [Adding Django Rest Framework](#adding-django-rest-framework)\n  - [Adding JWT - creating login and refresh views](#adding-jwt---creating-login-and-refresh-views)\n  - [Customizing JWT behavior](#customizing-jwt-behavior)\n  - [Customizing JWT token - include the username](#customizing-jwt-token---include-the-username)\n  - [Allowing Frontend Access with CORS](#allowing-frontend-access-with-cors)\n- [Frontend](#frontend)\n  - [Setting up webpages](#setting-up-webpages)\n  - [Protected routes](#protected-routes)\n  - [AuthContext - state management](#authcontext---state-management)\n      - [```createContext()```](#createcontext)\n      - [```useContext()```](#usecontext)\n  - [Login method](#login-method)\n  - [Logout method](#logout-method)\n  - [Keeping a user logged in after refresh](#keeping-a-user-logged-in-after-refresh)\n  - [UpdateToken method - Refreshing the access token](#updatetoken-method---refreshing-the-access-token)\n  - [Refreshing the Token on an Interval](#refreshing-the-token-on-an-interval)\n  - [Edge cases:](#edge-cases)\n- [User Permissions - control access to user-specific data](#user-permissions---control-access-to-user-specific-data)\n  - [Setting up user-specific data in django](#setting-up-user-specific-data-in-django)\n  - [Testing user permissions - displaying private profile info](#testing-user-permissions---displaying-private-profile-info)\n\n\u003c!-- TOC end --\u003e\n\n\u003c!-- TOC --\u003e\u003ca name=\"introduction\"\u003e\u003c/a\u003e\n# Introduction\n\nThis tutorial will walk through the process of implementing user authentication between a Django backend and a React frontend using JSON Web Tokens (JWT) with the help of [jwt.io](https://jwt.io). We'll start by setting up a basic Django backend with a user authentication system, then create a React frontend and integrate it with our backend. Finally, we'll implement JWT-based authentication to secure our web application, and access protected data. By the end of this tutorial, you'll have a solid understanding of how to use JWT to implement user authentication in a full-stack web application. For more discussion on why or why not to use JWT visit [here](https://blog.logrocket.com/jwt-authentication-best-practices/).\n\n\u003c!-- TOC --\u003e\u003ca name=\"what-is-jwt\"\u003e\u003c/a\u003e\n## What is JWT?\n\nJWT stands for JSON Web Token. It is an open standard for securely transmitting information between parties as a JSON object. In the context of web applications, JWTs are commonly used for authentication and authorization purposes.\n\nJWTs are useful because they allow a user to authenticate once and then securely transmit that authentication information between different parts of an application. This can eliminate the need to constantly re-authenticate a user, which can improve the overall user experience. JWTs are also stateless, which means that no server-side state needs to be stored, making them a good fit for distributed applications.\n\nDjango Rest Framework's built-in JWT functionality provides an easy way to use JWTs for authentication and authorization. When a user logs in, a JSON web token is generated by the server and sent to the client. The client then includes the token in subsequent requests to the server to prove that it has already been authenticated.\n\nWhen a request with a JWT is received by the server, the server validates the token by checking its signature and decoding the payload. If the token is valid, the server uses the information in the payload to authorize the request. If the token is not valid, the request is denied.\n\nSecurity is a critical aspect of using JWT for authentication and authorization. JWT tokens can potentially be intercepted and used by an attacker to gain unauthorized access to sensitive data or actions. It's important to properly secure tokens to prevent this. The tokens should be sent over HTTPS, and they should be properly validated to ensure they haven't been tampered with. It's also important to set a short expiration time for the access token to minimize the risk of an attacker using it. Django Rest Framework's JWT implementation includes measures to mitigate these risks, but it's still important to follow best practices to ensure the security of your application.\n\nFor more information on securing JWT in, see this post on [JWT Best Practice](https://curity.io/resources/learn/jwt-best-practices/).\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"backend\"\u003e\u003c/a\u003e\n# Backend\n\n\u003c!-- TOC --\u003e\u003ca name=\"boilerplate-setup\"\u003e\u003c/a\u003e\n## Boilerplate Setup\nTo start, we need a new Django project. In a shell, navigate to the directory you want to contain your project, and run \u003cbr\u003e```django-admin startproject backend```\n\nEnter the new project folder: \u003cbr\u003e```cd backend```\n\nBefore installing Django, you need to make sure that pipenv is installed. If you haven't installed it already, you can run:\u003cbr\u003e```pip install pipenv```\n\nThen, launch a virtual environment by calling \u003cbr\u003e```pipenv shell```\n\u003cbr\u003eThis creates a new virtual environment tied to this directory.\n\nFirst we need to install django in the new virtual env by running: \u003cbr\u003e```pip install django```\n\nNow we can create our app: \u003cbr\u003e```python manage.py startapp base```\n\nMake sure to run this command in the backend directory.\n\nIf you are using VSCode as your IDE, from here you can open the directory with ```code .```\n\nNow that there is a template in place, we are ready to start making changes. We want all the authentication api functionality to reside together, and to provide more separation for this functionality, we will create a new folder inside of ```/base``` called ```/api```.\n\nNow if everything has been setup correctly, when you run ```python manage.py runserver```, you should be able to see the server running on ```http://127.0.0.1:8000```\n\n\u003cbr\u003e\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"creating-a-view-and-routing-it\"\u003e\u003c/a\u003e\n## Creating a view and routing it\n\nOur goal here is to create a view that returns two API routes that will be used for sending user login details and receiving authentication tokens.\n\nThe first thing we want to do is create a new view and link it in the urls. In the api folder create two new files: ```urls.py``` and ```views.py```.  ```This urls.py``` folder will contain all of our user auth api routes; we will include it in the main url config file ```/base/urls.py``` later.\n\nThis is what the directory structure should look like:\n```\nbackend\n├── Pipfile\n├── Pipfile.lock\n├── README.md\n├── backend\n│   ├── README.md\n│   ├── __init__.py\n│   ├── asgi.py\n│   ├── settings.py\n│   ├── urls.py\n│   └── wsgi.py\n├── base\n│   ├── README.md\n│   ├── __init__.py\n│   ├── admin.py\n│   ├── api\n│   │   ├── README.md\n│   │   ├── urls.py\n│   │   └── views.py\n│   ├── apps.py\n│   ├── migrations\n│   │   ├── README.md\n│   │   └── __init__.py\n│   ├── models.py\n│   ├── tests.py\n│   └── views.py\n├── db.sqlite3\n└── manage.py\n```\n\nIn views.py create a new view that returns all the possible routes, here, we are going to have two routes: one for sending user login details and receiving authentication tokens ```/api/token```, and one for sending a refresh token and receiving new authentication tokens ```/api/token/refresh```.\n\n```python\nfrom django.http import JsonResponse\ndef get_routes(request):\n   routes = [\n       '/api/token',\n       '/api/token/refresh'\n   ]\n   return JsonResponse(routes, safe=False)\n```\nNote: The ```safe=False``` allows us to receive and display non-Json data\n\nTo link this view to an accessible url, we need to complete the ```urls.py``` file in our ```/api``` directory.\u003cbr\u003e```/api/urls.py```:\n```python\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n   path('', views.get_routes),\n]\n```\n\nNow to include the new url configuration in the app’s main url config file ```/backend/urls.py```, we need to import include and add a new path pointing to the ```/base/api/urls.py``` file \u003cbr\u003e```/backend/urls.py```:\n```python\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n   path('admin/', admin.site.urls),\n   path('api/', include('base.api.urls'))\n]\n```\n\nNow if you navigate to ```http://127.0.0.1:8000/api``` you should see these two routes displayed.\n\n\u003cbr\u003e\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"adding-django-rest-framework\"\u003e\u003c/a\u003e\n## Adding Django Rest Framework\n\nNow we want to use the Django Rest Framework for our API, the documentation for usage can be found [here](https://www.django-rest-framework.org/). To install make sure the virtual env is active and run\n\n```pip install djangorestframework```\n\nand modify the ```/backend/settings.py``` file\n```python\nINSTALLED_APPS = [\n    ...\n    'rest_framework',\n]\n```\n\nWe can change our view to use the django rest framwork by changing the response to use a DjangoRestFramework ```Response``` class instead of the default javascript ```JsonResponse```. Because this is a function based view, we also need to instruct it what kind of view we want to render with a decorator.\n\n```python\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\n@api_view(['GET'])\ndef get_routes(request):\n    \"\"\"returns a view containing all the possible routes\"\"\"\n    routes = [\n        '/api/token',\n        '/api/token/refresh'\n    ]\n\n    return Response(routes)\n```\n\nIf everything is configured correctly, you should see a new view at ```http://127.0.0.1:8000/api``` with an output that looks like this:\n```HTTP\nHTTP 200 OK\nAllow: OPTIONS, GET\nContent-Type: application/json\nVary: Accept\n\n[\n    \"/api/token\",\n    \"/api/token/refresh\"\n]\n```\n\n\u003cbr\u003e\n\n---\n\n## Adding JWT - creating login and refresh views\n\nLuckily, django rest framework has JWT built in. Following the documentation, to add it, we need to install it in the virtual env:\u003cbr\u003e```pip install djangorestframework-simplejwt```\n\nand configure it to be the default authentication behavior for django rest framework in the ```settings.py``` file by adding this setting:\n``` python\nREST_FRAMEWORK = {\n    ...\n    'DEFAULT_AUTHENTICATION_CLASSES': (\n        ...\n        'rest_framework_simplejwt.authentication.JWTAuthentication',\n    )\n    ...\n}\n```\n\nand add two urls for the login and refresh routes in ```/base/api/urls.py```\n\nthe new urls.py file should look like this:\n```python\nfrom django.urls import path\nfrom . import views\n\nfrom rest_framework_simplejwt.views import (\n    TokenObtainPairView,\n    TokenRefreshView,\n)\n\nurlpatterns = [\n    path('', views.get_routes),\n    path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n]\n```\n\nVerify jwt is working by first migrating the changes to the data model with \u003cbr\u003e```python manage.py migrate```\u003cbr\u003e then creating a superuser with \u003cbr\u003e```python manage.py createsuperuser```.\n\nNow when visiting ```http://127.0.0.1:8000/api/token/``` you should see input fields for a username and password. Login using the superuser login you just created.\n\nAfter POSTing your login credentials, you should receive a refresh and access token that looks like this:\n\n```HTTP\nHTTP 200 OK\nAllow: POST, OPTIONS\nContent-Type: application/json\nVary: Accept\n\n{\n    \"refresh\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY3NjU5MTcyMywiaWF0IjoxNjc2NTA1MzIzLCJqdGkiOiI2MTBlM2I4NTk3ZGQ0NGQ2YTk3MWViZTEwYzQzOTg3YiIsInVzZXJfaWQiOjF9.P5ps5AOBp25_HoeiatbC7_LZjoBBb0SxukvcpyvuaqI\",\n    \"access\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjc2NTA1NjIzLCJpYXQiOjE2NzY1MDUzMjMsImp0aSI6IjUxMTUzYTRiNmJkNjQyNTY4NDMzN2UyZjEyN2M2YTkwIiwidXNlcl9pZCI6MX0.O1n1TppJFk0KO8rUco1UWPaOcCyxaRPFOmIZv0Pte18\"\n}\n```\n\nCopy the refresh token you were just provided and then navigate to ```http://127.0.0.1:8000/api/token/refresh```, where you should see an input field for the refresh token. Paste and submit the refresh token. You should receive a new access token from the server if everything has worked.\n\n\u003cbr\u003e\n\n---\n\n## Customizing JWT behavior\n\nThere is a lot of potential customization to the behavior of JWT that can be found [here](https://django-rest-framework-simplejwt.readthedocs.io/en/latest/index.html), but I want to highlight a few that are of interest to us:\n```python\n\"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=5), # Specifies how long access tokens are valid. Typically use a lower value for higher security but more network overhead. Changing this will be useful for testing.\n\n\"REFRESH_TOKEN_LIFETIME\": timedelta(days=1), # Specifies how long refresh tokens are valid, this corresponds to how longer a user can remain logged in while not actively refreshing their tokens. Ex: if a user closes the tab for 22 hours, on reopening, the old refresh token would still be able to fetch a valid access token, continuing their authentication. Changing this will be useful for testing.\n\n\"ROTATE_REFRESH_TOKENS\": False, # When set to True, if a refresh token is submitted to the TokenRefreshView, a new refresh token will be returned along with the new access token. This provides a way to keep a rolling authentication while a client is open.\n\n\"BLACKLIST_AFTER_ROTATION\": False, # Causes refresh tokens submitted to the TokenRefreshView to be added to the blacklist. This prevents the scenario where a bad actor can use old refresh tokens to request their own new authentication tokens.\n```\n\nWhile ```ACCESS_TOKEN_LIFETIME``` and ```REFRESH_TOKEN_LIFETIME``` can remain as default for now, we want to change both ```ROTATE_REFRESH_TOKENS``` and ```BLACKLIST_AFTER_ROTATION``` to ```True```. Using the default settings from the documentation, we can add this section to the ```settings.py``` file with the new values.\n```python\nfrom datetime import timedelta\n...\n\nSIMPLE_JWT = {\n    \"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=5),\n    \"REFRESH_TOKEN_LIFETIME\": timedelta(days=1),\n    \"ROTATE_REFRESH_TOKENS\": True,\n    \"BLACKLIST_AFTER_ROTATION\": True,\n    \"UPDATE_LAST_LOGIN\": False,\n\n    \"ALGORITHM\": \"HS256\",\n    \"SIGNING_KEY\": SECRET_KEY,\n    \"VERIFYING_KEY\": \"\",\n    \"AUDIENCE\": None,\n    \"ISSUER\": None,\n    \"JSON_ENCODER\": None,\n    \"JWK_URL\": None,\n    \"LEEWAY\": 0,\n\n    \"AUTH_HEADER_TYPES\": (\"Bearer\",),\n    \"AUTH_HEADER_NAME\": \"HTTP_AUTHORIZATION\",\n    \"USER_ID_FIELD\": \"id\",\n    \"USER_ID_CLAIM\": \"user_id\",\n    \"USER_AUTHENTICATION_RULE\": \"rest_framework_simplejwt.authentication.default_user_authentication_rule\",\n\n    \"AUTH_TOKEN_CLASSES\": (\"rest_framework_simplejwt.tokens.AccessToken\",),\n    \"TOKEN_TYPE_CLAIM\": \"token_type\",\n    \"TOKEN_USER_CLASS\": \"rest_framework_simplejwt.models.TokenUser\",\n\n    \"JTI_CLAIM\": \"jti\",\n\n    \"SLIDING_TOKEN_REFRESH_EXP_CLAIM\": \"refresh_exp\",\n    \"SLIDING_TOKEN_LIFETIME\": timedelta(minutes=5),\n    \"SLIDING_TOKEN_REFRESH_LIFETIME\": timedelta(days=1),\n}\n```\nTo enable the blacklist, we need to add the blacklist app to our list of installed apps and migrate the assocaited data model changes:\n```python\nINSTALLED_APPS = [\n    ...\n    'rest_framework_simplejwt.token_blacklist',\n    ...\n]\n```\n```python manage.py migrate```\n\n\nNow when you visit ```http://127.0.0.1:8000/api/token/``` and login, and use the refresh token at ```http://127.0.0.1:8000/api/token/refresh/```, you should receive both a new access token and a new refresh token. You can also test the blacklist is functioning by trying to submit the same refresh token a second time. You should receive a response like this, indicating that token has already been used.\n\n```HTTP\nHTTP 401 Unauthorized\nAllow: POST, OPTIONS\nContent-Type: application/json\nVary: Accept\nWWW-Authenticate: Bearer realm=\"api\"\n\n{\n    \"detail\": \"Token is blacklisted\",\n    \"code\": \"token_not_valid\"\n}\n```\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"customizing-jwt-token-include-the-username\"\u003e\u003c/a\u003e\n## Customizing JWT token - include the username\n\nJWT tokens can be customized to include specific data. If you paste an access token into the debugger at [jwt.io](https://jwt.io/), you can see the payload data that it contains. This data usually includes the user_id, but what if we wanted to include the username as well without having to make a separate request to the server?\n\nTo do this, we can create a custom serializer that extends the ```TokenObtainPairSerializer``` class and overrides the ```get_token()``` method. In this method, we can add a new claim to the token, such as the username. The modified serializer looks like this:\n\n```python\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework_simplejwt.views import TokenObtainPairView\n\nclass MyTokenObtainPairSerializer(TokenObtainPairSerializer):\n    @classmethod\n    def get_token(cls, user):\n        token = super().get_token(user)\n        token['username'] = user.username\n        return token\n```\n\nNext, we need to create a custom view that uses our custom serializer instead of the default one. We can do this by creating a new view that extends the ```TokenObtainPairView``` class and sets its ```serializer_class``` attribute to our custom serializer. Here's what the new view looks like:\n```python\nfrom .serializers import MyTokenObtainPairSerializer\nfrom rest_framework_simplejwt.views import TokenObtainPairView\n\nclass MyTokenObtainPairView(TokenObtainPairView):\n    serializer_class = MyTokenObtainPairSerializer\n```\n\nFinally, we need to modify the URL to point to our new custom view. In our ```urls.py``` file, we replace ```TokenObtainPairView``` with ```MyTokenObtainPairView```:\n\n```python\nfrom django.urls import path\nfrom .views import MyTokenObtainPairView\nfrom rest_framework_simplejwt.views import TokenRefreshView\n\nurlpatterns = [\n    path('token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'),\n    path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n]\n```\n\n\u003c!-- TOC --\u003e\u003ca name=\"allowing-frontend-access-with-cors\"\u003e\u003c/a\u003e\n## Allowing Frontend Access with CORS\n\nTo allow requests from our frontend application, we need to set up Cross-Origin Resource Sharing (CORS) configuration for our Django project. The  [django-cors-headers](https://pypi.org/project/django-cors-headers/) library provides a simple way to enable CORS in our application.\n\nFirst, we need to install the ```django-cors-headers``` package by running the following command: \u003cbr\u003e ```pip install django-cors-headers```\n\nNext, add ```corsheaders``` to the ```INSTALLED_APPS``` list in the ```settings.py``` file:\n```python\nINSTALLED_APPS = [\n    ...,\n    \"corsheaders\",\n    ...,\n]\n```\nAfter that, add the ```CorsMiddleware``` to the ```MIDDLEWARE``` list:\n```python\nMIDDLEWARE = [\n    ...,\n    \"corsheaders.middleware.CorsMiddleware\",\n    \"django.middleware.common.CommonMiddleware\",\n    ...,\n]\n```\n\nNow we can configure the allowed origins in the ```settings.py``` file. For simplicity, we will allow all origins using the following setting:\n\n```python\nCORS_ALLOW_ALL_ORIGINS = True\n```\n\nNote that this setting should be modified to specify the allowed origins during deployment for security reasons.\n\nWith these settings, our Django backend is ready to receive requests from a frontend application.\n\n\u003cbr\u003e\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"frontend\"\u003e\u003c/a\u003e\n# Frontend\n\nTo create the frontend for our app, we will use ```npx create-react-app``` frontend to set up a new React application. This command generates a starter project with some boilerplate code that we can customize to fit our needs.\n\nWe are going to use ```npx create-react-app frontend``` for a  boilerplate of our react application.\n\nTo get started, navigate to the new directory with cd frontend. Next, we'll clean up some of the extra files that we won't be using, such as webVitals and the logo. In the ```/src``` folder, delete ```App.css```, ```App.test.js```, ```logo.svg```, ```reportWebVitals.js```, and ```setupTests.js```. Then modify ```App.js``` and ```index.js``` to remove all references to these deleted files:\n\n```App.js```:\n```javascript\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n\n```index.js```:\n```javascript\nimport React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport './index.css';\nimport App from './App';\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n  \u003cReact.StrictMode\u003e\n    \u003cApp /\u003e\n  \u003c/React.StrictMode\u003e\n);\n```\n\nAt this point, the directory should have the following structure:\n```\nfrontend\n├── node_modules\n├── package-lock.json\n├── package.json\n├── public\n│   ├── favicon.ico\n│   ├── index.html\n│   ├── logo192.png\n│   ├── logo512.png\n│   ├── manifest.json\n│   └── robots.txt\n└── src\n    ├── App.js\n    ├── index.css\n    └── index.js\n```\n\nNow we're ready to start building our application. We'll begin by adding some folders for organization. To start, let's create a ```/pages``` folder to contain our homepage (```HomePage.js```) and login page (```LoginPage.js```). We'll also need a header shared in common on both pages, so we'll add a ```/components``` folder to contain it and other shared components. To manage state, we'll create a ```/context/AuthContext.js``` file, which will use React's built-in Context API. Finally, we'll create a ```/utils``` folder for shared logic.\n\nAfter all these changes, the directory should look like this:\n\n```\nfrontend\n├── node_modules\n├── package-lock.json\n├── package.json\n├── public\n│   ├── favicon.ico\n│   ├── index.html\n│   ├── logo192.png\n│   ├── logo512.png\n│   ├── manifest.json\n│   └── robots.txt\n└── src\n    ├── App.js\n    ├── components\n    │   └── Header.js\n    ├── context\n    │   └── AuthContext.js\n    ├── index.css\n    ├── index.js\n    ├── pages\n    │   ├── HomePage.js\n    │   └── LoginPage.js\n    └── utils\n```\n\nWith this basic structure in place, we're ready to start building the frontend of our app.\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"setting-up-webpages\"\u003e\u003c/a\u003e\n## Setting up webpages\n\nLets start with a simple homepage. This page should only be visible to users who are logged in, but for now, we'll hardcode an ```isAuthenticated``` value for demonstration purposes only.\n\n```HomePage.js```:\n```javascript\nimport React from 'react'\n\nconst HomePage = () =\u003e {\n    const isAuthenticated = false;\n    return (\n        isAuthenticated ? (\n        \u003cdiv\u003e\n            \u003cp\u003eYou are logged in to the homepage!\u003c/p\u003e\n        \u003c/div\u003e\n        ):(\n        \u003cdiv\u003e\n            \u003cp\u003eYou are not logged in, redirecting...\u003c/p\u003e\n        \u003c/div\u003e\n        )\n    )\n}\n\nexport default HomePage\n```\n\nnext we can create a simple login page, but it wont work yet without a proper ```loginUser``` function, we'll define that later:\n\n```LoginPage.js```:\n```javascript\nimport React from 'react'\n\nconst LoginPage = () =\u003e {\n\n    let loginUser = (e) =\u003e {\n        e.preventDefault()\n    }\n\n    return (\n        \u003cdiv\u003e\n            \u003cform onSubmit={loginUser}\u003e\n                \u003cinput type=\"text\" name=\"username\" placeholder=\"Enter username\"/\u003e\n                \u003cinput type=\"password\" name=\"password\" placeholder=\"enter password\"/\u003e\n                \u003cinput type=\"submit\"/\u003e\n            \u003c/form\u003e\n        \u003c/div\u003e\n    )\n}\n\nexport default LoginPage\n```\n\nthe Header component will responsible for displaying the navigation links and user information, and it is included in the App component so that it appears on every page. Again we are using a filler function for handling logging out a user for now:\n\n```Header.js```:\n```javascript\nimport React, { useState } from 'react'\nimport { Link } from 'react-router-dom'\n\nconst Header = () =\u003e {\n    let [user, setUser] = useState(null)\n    let logoutUser = (e) =\u003e {\n        e.preventDefault()\n    }\n    return (\n        \u003cdiv\u003e\n            \u003cLink to=\"/\"\u003eHome\u003c/Link\u003e\n            \u003cspan\u003e | \u003c/span\u003e\n            {user ? (\n                \u003cp onClick={logoutUser}\u003eLogout\u003c/p\u003e\n            ) : (\n                \u003cLink to=\"/login\" \u003eLogin\u003c/Link\u003e\n            )}\n            {user \u0026\u0026 \u003cp\u003eHello {user.username}!\u003c/p\u003e}\n\n        \u003c/div\u003e\n    )\n}\n\nexport default Header\n```\n\nWe need to setup all the url routing for these pages in ```App.js```. To do this we need to install the ```react-router-dom``` package with ```npm install react-router-dom```. It is used to handle routing, its documentation can be found [here](https://reactrouter.com/en/main).\n\n```App.js```:\n```javascript\nimport { BrowserRouter as Router, Route, Routes } from 'react-router-dom'\n\nimport HomePage from './pages/HomePage'\nimport LoginPage from './pages/LoginPage'\nimport Header from './components/Header'\n\nfunction App() {\n    return (\n        \u003cdiv className=\"App\"\u003e\n            \u003cRouter\u003e\n                \u003cHeader/\u003e\n                \u003cRoutes\u003e\n                    \u003cRoute path=\"/\" element={\u003cHomePage/\u003e} /\u003e\n                    \u003cRoute path=\"/login\" element={\u003cLoginPage/\u003e}/\u003e\n                \u003c/Routes\u003e\n            \u003c/Router\u003e\n        \u003c/div\u003e\n    );\n}\n\nexport default App;\n```\nWe are finally ready to launch the frontend. Make sure youre in the ```/frontend``` directory and run ```npm start``` in the console. A development server should launch on ```localhost:3000```.\n\nyou should be able to see the homepage, and if you click the Login link in the header, you should be directed to the login page.\n\n\u003cbr\u003e\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"protected-routes\"\u003e\u003c/a\u003e\n## Protected routes\nWhen a user visits the homepage without being authenticated, they should be redirected to the login page. This type of page is called a private route, one that requires authentication to view. To add private routes, we first need to define a component in ```utils/PrivateRoute.js```.\n\n```javascript\nimport { Navigate } from 'react-router-dom'\nimport { useState } from 'react'\n\nconst PrivateRoute = ({children, ...rest}) =\u003e {\n    let [user, setUser] = useState(null)\n\n    return !user ? \u003cNavigate to='/login'/\u003e : children;\n}\n\nexport default PrivateRoute;\n```\n\nThis component checks if a client is authenticated. If so, the rendering continues uninterrupted. Otherwise, the client is redirected to the login page. We've used a separate state to store the user here, but we want this user state to match the user state in the header. This is where context state management comes in, and we'll cover that later.\n\nTo protect a route, we just need to wrap the ```Route``` component in a ```\u003cPrivateRoute\u003e``` component like so:\n\n```javascript\n\u003cRoutes\u003e\n    ...\n    \u003cRoute path=\"/\" element={\u003cPrivateRoute\u003e\u003cHomePage/\u003e\u003c/PrivateRoute\u003e} /\u003e\n    ...\n\u003c/Routes\u003e\n```\n\nThis protects the homepage route, meaning a user cannot access the page until they are authenticated, and will instead be redirected to the login page.\n\nHere's the updated ```App.js``` file with a protected homepage:\n\n```javascript\nimport { BrowserRouter as Router, Route, Routes } from 'react-router-dom'\n\nimport HomePage from './pages/HomePage'\nimport LoginPage from './pages/LoginPage'\nimport Header from './components/Header'\n\nimport PrivateRoute from './utils/PrivateRoute'\n\n\nfunction App() {\n  return (\n    \u003cdiv className=\"App\"\u003e\n        \u003cRouter\u003e\n            \u003cHeader/\u003e\n            \u003cRoutes\u003e\n                \u003cRoute path=\"/\" element={\u003cPrivateRoute\u003e\u003cHomePage/\u003e\u003c/PrivateRoute\u003e} /\u003e\n                \u003cRoute path=\"/login\" element={\u003cLoginPage/\u003e}/\u003e\n            \u003c/Routes\u003e\n        \u003c/Router\u003e\n    \u003c/div\u003e\n  );\n}\n\nexport default App;\n```\n\nNow you should be unable to load the homepage until a user is authenticated, and will instead be redirected to the login page.\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"authcontext-state-management\"\u003e\u003c/a\u003e\n## AuthContext - state management\n\nWe want to save the authentication tokens and user state and use it throughout the application, so to avoid prop drilling or other more complicated options, we'll use the useContext hook built into React.\n\n\u003c!-- TOC --\u003e\u003ca name=\"createcontext\"\u003e\u003c/a\u003e\n#### ```createContext()```\n```createContext()``` is a function provided by the React library that allows you to create a context object. This object provides a way to pass data between components without having to pass props down through the component tree. It consists of a provider component that wraps the other components and passes data down to them, and a consumer component that accesses the data passed down from the provider.\n\nIn this case, we use the createContext() function to create an AuthContext object, which we then export and use as a shared state across our application. We define the initial state and any methods that we want to share in the AuthProvider component, and then wrap our components with this provider so that they have access to this shared state.\n\nTo start we will define the state we know we want shared across our application in an ```AuthProvider``` component, including a ```user```, ```authTokens```, ```loginUser``` method and ```logoutUser``` method.\n\n```javascript\nimport { createContext, useState } from 'react'\n\nconst AuthContext = createContext()\n\nexport default AuthContext;\n\nexport const AuthProvider = ({children}) =\u003e {\n\n    let [user, setUser] = useState(null)\n    let [authTokens, setAuthTokens] = useState(null)\n\n    let loginUser = async (e) =\u003e {\n        e.preventDefault()\n    }\n\n    let logoutUser = (e) =\u003e {\n        e.preventDefault()\n    }\n\n    let contextData = {\n        user: user,\n        authTokens: authTokens,\n        loginUser: loginUser,\n        logoutUser: logoutUser,\n    }\n\n    return(\n        \u003cAuthContext.Provider value={contextData}\u003e\n            {children}\n        \u003c/AuthContext.Provider\u003e\n    )\n}\n```\n\nThen we can provide this state to the other components by wrapping them in an ```\u003cAuthProvider\u003e``` component:\n\n```App.js```\n```javascript\nimport { BrowserRouter as Router, Route, Routes } from 'react-router-dom'\n\nimport { AuthProvider } from './context/AuthContext'\n\nimport HomePage from './pages/HomePage'\nimport LoginPage from './pages/LoginPage'\nimport Header from './components/Header'\n\nimport PrivateRoute from './utils/PrivateRoute'\n\n\nfunction App() {\n    return (\n        \u003cdiv className=\"App\"\u003e\n            \u003cRouter\u003e\n                \u003cAuthProvider\u003e\n                \u003cHeader/\u003e\n                \u003cRoutes\u003e\n                    \u003cRoute path=\"/\" element={\n                        \u003cPrivateRoute\u003e\n                            \u003cHomePage/\u003e\n                        \u003c/PrivateRoute\u003e}/\u003e\n                    \u003cRoute path=\"/login\" element={\u003cLoginPage/\u003e}/\u003e\n                \u003c/Routes\u003e\n                \u003c/AuthProvider\u003e\n            \u003c/Router\u003e\n        \u003c/div\u003e\n    );\n}\n\nexport default App;\n```\n\u003c!-- TOC --\u003e\u003ca name=\"usecontext\"\u003e\u003c/a\u003e\n#### ```useContext()```\nuseContext() is a hook provided by the React library that allows you to consume the data and methods passed down by a context provider. It takes in a context object created by createContext() and returns the current value of the context.\n\nIn our application, we use useContext() to access the shared state and methods defined in our AuthContext object. We call useContext(AuthContext) inside our components to access the current user state, authentication tokens, login function, and logout function. This allows us to avoid prop drilling and pass data and methods down from the top-level component to the components that need them.\n\nE.g.\n```javascript\nlet { user, loginUser } = useContext(AuthContext)\n```\n\nWe need to make this change in 4 places:\n\n1. ```Header.js```, after adjusting to use the shared context and ```logoutUser``` method, looks like:\n\n```javascript\nimport React, { useContext } from 'react'\nimport { Link } from 'react-router-dom'\nimport AuthContext from '../context/AuthContext'\n\nconst Header = () =\u003e {\n    let { user, logoutUser } = useContext(AuthContext)\n\n    return (\n        \u003cdiv\u003e\n            \u003cLink to=\"/\"\u003eHome\u003c/Link\u003e\n            \u003cspan\u003e | \u003c/span\u003e\n            {user ? (\n                \u003cp onClick={logoutUser}\u003eLogout\u003c/p\u003e\n            ) : (\n                \u003cLink to=\"/login\" \u003eLogin\u003c/Link\u003e\n            )}\n            {user \u0026\u0026 \u003cp\u003eHello {user.username}!\u003c/p\u003e}\n\n        \u003c/div\u003e\n    )\n}\n\nexport default Header\n```\n\n2. ```LoginPage.js```, after adjusting to use the shared ```loginUser``` method, looks like:\n```javascript\nimport React, {useContext} from 'react'\nimport AuthContext from '../context/AuthContext'\n\nconst LoginPage = () =\u003e {\n\n    let {loginUser} = useContext(AuthContext)\n\n    return (\n        \u003cdiv\u003e\n            \u003cform onSubmit={loginUser}\u003e\n                \u003cinput type=\"text\" name=\"username\" placeholder=\"Enter username\"/\u003e\n                \u003cinput type=\"password\" name=\"password\" placeholder=\"enter password\"/\u003e\n                \u003cinput type=\"submit\"/\u003e\n            \u003c/form\u003e\n        \u003c/div\u003e\n    )\n}\n\nexport default LoginPage\n```\n\n3. ```Homepage.js``` is also adjusted to use the AuthContext for user state:\n```javascript\nimport React, { useContext } from 'react'\nimport AuthContext from '../context/AuthContext';\n\nconst HomePage = () =\u003e {\n    const { user } = useContext(AuthContext);\n\n    return (user ? (\n        \u003cdiv\u003e\n            \u003cp\u003eYou are logged in to the homepage!\u003c/p\u003e\n        \u003c/div\u003e\n        ):(\n        \u003cdiv\u003e\n            \u003cp\u003eYou are not logged in, redirecting...\u003c/p\u003e\n        \u003c/div\u003e\n        )\n    )\n}\n\nexport default HomePage\n```\n\n4. The last place to make this change is in ```PrivateRoute.js```\n```javascript\nimport { Navigate } from 'react-router-dom'\nimport { useContext } from 'react'\nimport AuthContext from '../context/AuthContext';\n\nconst PrivateRoute = ({children, ...rest}) =\u003e {\n    let { user } = useContext(AuthContext)\n\n    return !user ? \u003cNavigate to='/login'/\u003e : children;\n}\n\nexport default PrivateRoute;\n```\n\nwe can test this is working by changing the state of user in AuthContext.js and verifying that our header now shows a greeting to the user and offers a logout option instead of a login option.\n\n```javascript\nlet [user, setUser] = useState({username:'Sean'})\n```\n\nreturn the state to null after testing.\n\n\u003c!-- TOC --\u003e\u003ca name=\"login-method\"\u003e\u003c/a\u003e\n## Login method\n\nThe loginUser method is responsible for handling the user's login attempt by submitting a POST request to the backend server with the user's login credentials. The response should contain auth tokens, which need to be decoded so that the payload data can be read. The [jwt-decode](https://www.npmjs.com/package/jwt-decode) package can be installed to help with this. ```npm install jwt-decode```\n\nIf the POST request is successful, the newly received tokens and the successfully logged-in user should be stored in state, and the tokens saved in local storage. The user should then be redirected to their homepage. If there is an error, an alert should be shown.\n\nHere's the code for the entire AuthProvider component, with the new method:\n```javascript\nimport { createContext, useState } from 'react'\nimport jwtDecode from 'jwt-decode';\nimport { useNavigate } from 'react-router-dom'\n\nconst AuthContext = createContext()\n\nexport default AuthContext;\n\nexport const AuthProvider = ({children}) =\u003e {\n\n    let [user, setUser] = useState(null)\n    let [authTokens, setAuthTokens] = useState(null)\n\n    const navigate = useNavigate()\n\n    let loginUser = async (e) =\u003e {\n        e.preventDefault()\n        const response = await fetch('http://127.0.0.1:8000/api/token/', {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/json'\n            },\n            body: JSON.stringify({username: e.target.username.value, password: e.target.password.value })\n        });\n\n        let data = await response.json();\n\n        if(data){\n            localStorage.setItem('authTokens', JSON.stringify(data));\n            setAuthTokens(data)\n            setUser(jwtDecode(data.access))\n            navigate('/')\n        } else {\n            alert('Something went wrong while loggin in the user!')\n        }\n    }\n\n    let logoutUser = (e) =\u003e {\n        e.preventDefault()\n    }\n\n    let contextData = {\n        user: user,\n        authTokens: authTokens,\n        loginUser: loginUser,\n        logoutUser: logoutUser,\n    }\n\n    return(\n        \u003cAuthContext.Provider value={contextData}\u003e\n            {children}\n        \u003c/AuthContext.Provider\u003e\n    )\n}\n```\n\nAfter submitting the superuser credentials on the login page, if the request is successful, the user should be logged in and redirected to the home page.\n\n\u003c!-- TOC --\u003e\u003ca name=\"logout-method\"\u003e\u003c/a\u003e\n## Logout method\n\nThe logout link isn't working yet, so let's fix that. To logout a user, we need to\n    - Clear the ```localStorage``` by removing the stored authentication tokens\n    - Update the state of the ```authTokens``` and ```user``` to null, effectively logging the user out\n    - Redirect the user is redirected to the login page using the ```navigate``` method from ```react-router-dom```:\n\n```javascript\nlet logoutUser = (e) =\u003e {\n    e.preventDefault()\n    localStorage.removeItem('authTokens')\n    setAuthTokens(null)\n    setUser(null)\n    navigate('/login')\n}\n```\n\nNow when you click on the logout link, you should be logged out and redirected to the login page. Confirm the ```localStorage``` is cleared in the storage tab of the developer tools.\n\n---\n\n\u003c!-- TOC --\u003e\u003ca name=\"keeping-a-user-logged-in-after-refresh\"\u003e\u003c/a\u003e\n## Keeping a user logged in after refresh\n\nAfter submitting login details and being redirected to the homepage, refreshing the page logs the user out. To prevent this, we can use JSON Web Tokens (JWT) stored in localStorage to automatically log the user back in without requiring login credentials.\n\nTo achieve this, we need to update the initial state of the user and authTokens variables in AuthContext.js to check the localStorage for authTokens before setting them to null if none are found. We can use a callback function in the useState hook to ensure that this logic is only executed once on the initial load of AuthProvider, and not on every rerender.\n\nHere are the updated lines of code:\n\n```AuthContext.js```\n```javascript\nlet [user, setUser] = useState(() =\u003e (localStorage.getItem('authTokens') ? jwtDecode(localStorage.getItem('authTokens')) : null))\nlet [authTokens, setAuthTokens] = useState(() =\u003e (localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null))\n```\n\nAfter submitting login credentials, redirecting to the homepage, and refreshing the page, the user should remain logged in.\n\n---\n\n## UpdateToken method - Refreshing the access token\n\nThe access token, as currently configured, has a limited lifetime of 5 minutes, after which a new one must be generated using the refresh token. To handle this, we need to create an ```updateToken``` method. This is the setting of interest:\n\n```python\n...\n\"ACCESS_TOKEN_LIFETIME\": timedelta(minutes=5),\n...\n```\n\nThe updateToken method sends a POST request to ```http://127.0.0.1:8000/api/token/refresh/``` containing the refresh token, and receives a new access token and refresh token to save in ```localStorage``` and update the context state. If an invalid refresh token is used, the user is logged out. Here is the code for the ```updateToken``` method:\n\n```javascript\nconst updateToken = async () =\u003e {\n        const response = await fetch('http://127.0.0.1:8000/api/token/refresh/', {\n            method: 'POST',\n            headers: {\n                'Content-Type':'application/json'\n            },\n            body:JSON.stringify({refresh:authTokens?.refresh})\n        })\n\n        const data = await response.json()\n        if (response.status === 200) {\n            setAuthTokens(data)\n            setUser(jwtDecode(data.access))\n            localStorage.setItem('authTokens',JSON.stringify(data))\n        } else {\n            logoutUser()\n        }\n\n        if(loading){\n            setLoading(false)\n        }\n    }\n```\n\n## Refreshing the Token on an Interval\n\nTo keep the user authenticated, we need to refresh their access token before it expires. In our case, we will refresh the token every 4 minutes to avoid the possibility of a slow server response causing the user to be logged out. This approach has obvious drawbacks, and surely a better and more popular approach would be to refresh these tokens on every call to the server with Axios interceptors. I plan to explore this in the future, but for now we will update the tokens on an interval using the ```useEffect``` hook. Here is the code for that ```useEffect``` hook:\n\n```javascript\nlet [loading, setLoading] = useState(true)\n\nuseEffect(()=\u003e{\n\n        const REFRESH_INTERVAL = 1000 * 60 * 4 // 4 minutes\n        let interval = setInterval(()=\u003e{\n            if(authTokens){\n                updateToken()\n            }\n        }, REFRESH_INTERVAL)\n        return () =\u003e clearInterval(interval)\n\n    },[authTokens])\n```\n\nThe useEffect hook uses JavaScript's built-in ```setInterval``` function to execute a callback function at a set interval in milliseconds. We need to clear the existing interval when the hook is triggered again to avoid multiple intervals being created. We also need to track when the page is loading using the ```loading``` state, which is initially set to ```true```.\n\n---\n\nOur new ```AuthContext.js```:\n```javascript\nimport { createContext, useState, useEffect } from 'react'\nimport jwtDecode from 'jwt-decode';\nimport { useNavigate } from 'react-router-dom'\n\nconst AuthContext = createContext()\n\nexport default AuthContext;\n\nexport const AuthProvider = ({children}) =\u003e {\n\n    let [user, setUser] = useState(() =\u003e (localStorage.getItem('authTokens') ? jwtDecode(localStorage.getItem('authTokens')) : null))\n    let [authTokens, setAuthTokens] = useState(() =\u003e (localStorage.getItem('authTokens') ? JSON.parse(localStorage.getItem('authTokens')) : null))\n    let [loading, setLoading] = useState(true)\n\n    const navigate = useNavigate()\n\n    let loginUser = async (e) =\u003e {\n        e.preventDefault()\n        const response = await fetch('http://127.0.0.1:8000/api/token/', {\n            method: 'POST',\n            headers: {\n                'Content-Type': 'application/json'\n            },\n            body: JSON.stringify({username: e.target.username.value, password: e.target.password.value })\n        });\n\n        let data = await response.json();\n\n        if(data){\n            localStorage.setItem('authTokens', JSON.stringify(data));\n            setAuthTokens(data)\n            setUser(jwtDecode(data.access))\n            navigate('/')\n        } else {\n            alert('Something went wrong while logging in the user!')\n        }\n    }\n\n    let logoutUser = (e) =\u003e {\n        e.preventDefault()\n        localStorage.removeItem('authTokens')\n        setAuthTokens(null)\n        setUser(null)\n        navigate('/login')\n    }\n\n    const updateToken = async () =\u003e {\n        const response = await fetch('http://127.0.0.1:8000/api/token/refresh/', {\n            method: 'POST',\n            headers: {\n                'Content-Type':'application/json'\n            },\n            body:JSON.stringify({refresh:authTokens?.refresh})\n        })\n\n        const data = await response.json()\n        if (response.status === 200) {\n            setAuthTokens(data)\n            setUser(jwtDecode(data.access))\n            localStorage.setItem('authTokens',JSON.stringify(data))\n        } else {\n            logoutUser()\n        }\n\n        if(loading){\n            setLoading(false)\n        }\n    }\n\n    let contextData = {\n        user:user,\n        authTokens:authTokens,\n        loginUser:loginUser,\n        logoutUser:logoutUser,\n    }\n\n    useEffect(()=\u003e{\n        const REFRESH_INTERVAL = 1000 * 60 * 4 // 4 minutes\n        let interval = setInterval(()=\u003e{\n            if(authTokens){\n                updateToken()\n            }\n        }, REFRESH_INTERVAL)\n        return () =\u003e clearInterval(interval)\n\n    },[authTokens])\n\n    return(\n        \u003cAuthContext.Provider value={contextData}\u003e\n            {children}\n        \u003c/AuthContext.Provider\u003e\n    )\n}\n```\n\n---\n\n## Edge cases:\n\nLet's consider an edge case where the ```REFRESH_TOKEN_LIFETIME``` setting on the backend is set to a short duration, say 5 seconds. After logging in, if a token refresh is triggered, you'll receive a ```401 Unauthorized access``` response when a call is made to update the tokens. This is because the refresh token has expired, and login credentials are required to authenticate the user again. To simulate this edge case, you can set the token refresh interval to 10000 ms (10 seconds).\n\nTo ensure that a user is logged out and redirected to the login page when accessing a protected route with an expired access token, and is not logged out and redirected while waiting for a response to an ```updateToken``` request, we need to keep track of when the ```AuthProvider``` is first loaded. We can achieve this by initializing a new state variable, ```loading```, to ```true```:\n\n```javascript\nlet [loading, setLoading] = useState(true)\n```\n\nIf the state is ```loading```, we want to attempt to update the tokens at the beginning of the ```useEffect``` hook. This will fetch new refresh tokens where possible, and redirect users with invalid tokens back to the login screen:\n\n```javascript\nuseEffect(()=\u003e{\n    if(loading){\n        updateToken()\n    }\n    ...\n},[authTokens, loading])\n```\n\nFinally, at the end of the ```updateToken()``` function, set the ```loading``` state to ```false```:\n\n```javascript\nconst updateToken = async () =\u003e {\n    ...\n    if(loading){\n        setLoading(false)\n    }\n}\n```\n\nWith this approach, we ensure that the user is logged out and redirected to the login page only when the access token has expired, and not while waiting for a response to an updateToken request.\n\n# User Permissions - control access to user-specific data\nTo control access to user-specific data, we need to extend the default Django ```User``` model by adding a ```Profile``` model with a one-to-one relationship. The ```Profile``` model will contain private information such as first name, last name, and email. We will display each user their own profile information when on the home page.\n\n## Setting up user-specific data in django\nTo start we need to return to the backend and add the ```Profile``` model to the ```models.py``` file:\n\n```models.py```\n```python\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\nclass Profile(models.Model):\n    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')\n    first_name = models.CharField(max_length=100)\n    last_name = models.CharField(max_length=100)\n    email = models.EmailField()\n\n    def __str__(self):\n        return self.user.username\n```\nWe also need a serializer for the new ```Profile``` model. Create a ```serializers.py``` file inside the ```/base``` directory. We define a simple serializer for ```User``` so we can nest it inside the ```ProfileSerializer```:\n\n```serializers.py```\n```python\nfrom rest_framework import serializers\nfrom base.models import *\n\nclass UserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = '__all__'\n\nclass ProfileSerializer(serializers.ModelSerializer):\n    user = UserSerializer(many=False, read_only=True)\n    class Meta:\n        model = Profile\n        fields = ('user', 'first_name', 'last_name', 'email')\n```\n\nWe make this data available via the``` /api``` route with a new view. We use a new decorator from the Django REST framework, ```@permission_classes``` to verify that the user is authenticated with ```request.user``` before any of the other code in the view is executed: (Documentation on permissions can be found [here](https://www.django-rest-framework.org/api-guide/permissions/))\n\n```python\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef get_profile(request):\n    user = request.user\n    profile = user.profile\n    serializer = ProfileSerializer(profile, many=False)\n    return Response(serializer.data)\n```\n\nthen we can link this view in the ```urls.py``` file:\n\n```python\nurlpatterns = [\n    path('profile/', views.get_profile),\n    ...\n]\n```\n\n---\n\n## Testing user permissions - displaying private profile info\n\nTo test user permissions, we need to migrate the data model changes with:\n\n```python manage.py makemigrations```\n\n```python manage.py migrate```\n\nYou may need to delete all previous users or add ```null=True``` to the model fields to migrate the changes.\n\nCreate two users, each with associated profiles:\n\ne.g.\n```\nusername: \"user1\",\npassword: \"password1\",\nprofile: {\n    first_name: \"Sam\",\n    last_name: \"Smith\",\n    email: \"sam@smith.com\"\n}\n\nusername: \"user2\",\npassword: \"password2\",\nprofile: {\n    first_name: \"Tim\",\n    last_name: \"Allen\",\n    email: \"tim@allen.com\"\n}\n\n```\n\nIf you try to access ```http://127.0.0.1:8000/api/profile``` now, you will get an ```\"Unauthorized\"``` response. By default, the GET request does not include any authentication details. To authenticate, we need to go back to the frontend and change our homepage to render these details specific to the authenticated user. We have defined a ```getProfile()``` function to fetch the profile data from the server, including our auth access token with the GET request. We have also added a state to store our profile data. (If this data were used in other places throughout the application, you may consider moving this to a context for shared state management.) Lastly, the ```useEffect``` hook is used to fetch the profile data once on the first load of the component, provided the blank dependency array.\n\n```HomePage.js```\n```javascript\nimport React, { useState, useEffect, useContext } from 'react'\nimport AuthContext from '../context/AuthContext';\n\nconst HomePage = () =\u003e {\n    const { authTokens, logoutUser } = useContext(AuthContext);\n    let [profile, setProfile] = useState([])\n\n    useEffect(() =\u003e {\n        getProfile()\n    },[])\n\n    const getProfile = async() =\u003e {\n        let response = await fetch('http://127.0.0.1:8000/api/profile', {\n        method: 'GET',\n        headers:{\n            'Content-Type': 'application/json',\n            'Authorization':'Bearer ' + String(authTokens.access)\n        }\n        })\n        let data = await response.json()\n        console.log(data)\n        if(response.status === 200){\n            setProfile(data)\n        } else if(response.statusText === 'Unauthorized'){\n            logoutUser()\n        }\n    }\n\n    return (\n        \u003cdiv\u003e\n            \u003cp\u003eYou are logged in to the homepage!\u003c/p\u003e\n            \u003cp\u003eName: {profile.first_name} {profile.last_name}\u003c/p\u003e\n            \u003cp\u003eEmail: {profile.email}\u003c/p\u003e\n        \u003c/div\u003e\n    )\n}\n\nexport default HomePage\n```\n\nNow when you navigate to ```http://localhost:3000/login``` and login with (```username: \"user1\", password: \"password1\"```) you should see the profile details for this user on the home page:\n```\n    Name: Sam Smith\n    Email: sam@smith.com\n```\n\nand when you login to a different user (```username: \"user2\", password: \"password2\"```) you should see their profile details:\n```\n    Name: Tim Allen\n    Email: tim@allen.com\n```\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseankwarren%2Fdjango-react-jwt-authentication","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fseankwarren%2Fdjango-react-jwt-authentication","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fseankwarren%2Fdjango-react-jwt-authentication/lists"}