Git Product home page Git Product logo

react_persist_login's Introduction

"React Persistent User Login Authentication with JWT Tokens"

โœ… Check out my YouTube Channel with all of my tutorials.

Description:

This repository shares the code applied during the YouTube Tutorial.

Build the backend REST API that I use for authentication in this tutorial with my 7 hour Node JS for Beginners course on my channel.

Just starting with React? I have a 9 hour React course tutorial video on my channel.

I suggest completing my 8 hour JavaScript course tutorial video before attempting React if you are new to Javascript.

Academic Honesty

DO NOT COPY FOR AN ASSIGNMENT - Avoid plagiargism and adhere to the spirit of this Academic Honesty Policy.

react_persist_login's People

Contributors

gitdagray avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react_persist_login's Issues

Interceptors in combinatie with SWR

I have been following your tutorials in creating a react app. The persistent login works perfectly. The axios interceptors do their job. But fetching data is still done in a useEffect() hook. It seems this is no longer the way to go. I'm switching to SWR and fetching data is very simple if no authentication is required.

But i'm having trouble implementing the axiosPrivate interceptors. Would you be so kind to give me a nudge in the right direction on how to use the interceptors in useAxiosPrivate in combinatie with SWR?

EDIT: maybe i should add how far i got:
const { data: missions, isLoading, error } = useSWR('GetMissions', async ()=>{const response = await axiosPrivate(axiosUrls('GetAllMissions')); return response.data}, { onSuccess(data, key, config) { console.log(data) } })

The axiosUrls is just a list of endpoints. This executes without react warnings but i'm getting the 401 Unauthorized response. On checking the request, it seems the accesstoken isn't added to the header.

Using useEffect (like in your User component), this is the request
useEffect

When used in useSWR, this is the request
useSWR

SetAuth - does not work

It always causes the catch of the axios to err in Login.js
console.log(JSON.stringify(response?.data));
const user = response?.data?.csrf_token;
//const roles = response?.data?.roles;
setAuth({user});
//setUser('');
//setPwd('');
//navigate(from, { replace: true });
} catch (err) {
if (!err?.response) {
setErrMsg('Servers are down, please try again later.');

even the server response is 200 and csrf token is fetched, the setAuth does not set it for some reason and err is triggered by catch?

What I could be missing here?

[Question] Does the refresh token API require the logged-in user email and the refresh token values on the body parameters?

Hi Dave,

I'm Jabal. I'm a frontend engineer using React Js.
Sorry if I create an issue in your repository. I just want to ask something about the token management in React Js.

I have watched your token management videos on React Js. I really loved them.
I have been using the browser's local storage to store the user profile and the JWT tokens (access token and the refresh token values) for more than one year.
After watching and learning about your amazing videos, I tried to migrate from using the browser's local storage into using the browser cookies and React Context API to store the user profile and the JWT tokens.
Sadly, almost all of my friends and coworkers still use the browser's local storage for storing the user profile and the JWT tokens.

My question is:

  • If we want to store the user profile and the JWT tokens in the browser cookies and use the React Context API, does the refresh token API (made by the backend team) require the logged-in user email and the refresh token values on the body parameters?

I have worked on several projects with different backend teams. All of the backend teams made the refresh token API require the logged-in user email and the refresh token values on the body parameters.
For example this documentation snippet below:

Headers:
{
    "Content-Type": "application/json"
}

Body:
{
    "email": "[email protected]",
    "refreshToken": "{{refresh-token}}"
}

I saw from your useRefreshToken.js code on this repository that the frontend app didn't send the the logged-in user email and the refresh token values for your refresh token API.

const response = await axios.get('/refresh', {
    withCredentials: true
});

The code above only sends the withCredentials field (I predict that it's the cookies that store the JWT tokens).

Then, I have another question:

  • If the refresh token API (made by my backend teams) needs the logged-in user email and the refresh token, where should I store the logged-in user email and the refresh token values (besides using the browser's local storage and React Context API)?

If I store the logged-in user email and the refresh token values using the React Context API then I refresh the browser's page, the frontend app wouldn't recognize the logged-in user email and the refresh token because React Context API is just a temporary browser memory.

I haven't watched your Node Js tutorial video because of my current workload, I haven't got any time to learn the backend.
I predict that if the frontend wants to use cookies and React Context API for storing the user profile and the JWT tokens, the frontend should only send the withCredentials field (without the logged-in user email and the refresh token values) and the backend should process the credentials sent by the frontend.

  • Is my last statement above correct?

I really want to implement something great I learned like using cookies and React Context API for storing the user credentials.

When I refresh twice, I get logged out.

When I refresh the page twice, i get logged out. If I refresh only once, I do not get logged out.

import { Outlet } from 'react-router-dom'
import { useState, useEffect } from 'react'
import useRefreshToken from '../hooks/useRefreshToken'
import useAuth from '../hooks/useAuth'

const PersistLogin = () => {
const [ isLoading, setIsLoading ] = useState(true)
const refresh = useRefreshToken()
const { auth } = useAuth()

useEffect(() => {
    let isMounted = true

    const verifyRefreshToken = async () => {
        try{
            await refresh()
        }catch (err){
            console.log(err)
        }
        finally{
            // Avoids unwanted call to verifyRefreshToken
            isMounted && setIsLoading(false)
        }
    }
    !auth?.accessToken  ? verifyRefreshToken() : setIsLoading(false);

    return () => isMounted = false
},[])

useEffect(() => {
    console.log(`isLoading : ${isLoading}`)
    console.log(`authToken : ${JSON.stringify(auth?.accessToken)}`)
},[isLoading])

return (
<>
{isLoading
?

...Loading


:
}
</>
)
}

export default PersistLogin

Running in strict mode, in dev - accessing Admin (and users) instantly navigates to login

I may have introduced a bug, but when I run this using Strict mode in development, React mounts and then instantly unmounts the Users component. This cancels the axios request that was initiated by the use effect.

Canceling that request triggers the catch block on lines 22-25, which navigates the user to the login screen.

So, any time I navigate to the Admin/Users route, I'm instantly navigated to the Login screen.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.