How to implement remember me functionality for authentication in ReactJS when i only receive jwt token from backend api
Asked Answered
F

6

11

I currently have to implement remember functionality for remembering my login info on my frontend website. How to implement remember me functionality for authentication in ReactJS when i only receive jwt token from backend API.

Fredericfrederica answered 15/12, 2020 at 3:31 Comment(0)
P
15

Once you receive a jwt token, you can set an "expiry time" for your jwt token. For example, if I receive a token with id: "abc_token_123", I will create an object inside sessionstorage, localstorage, or even cookies with a key called expireTime (for example). And I will use a useEffect hook on the main file (App.js) to watch for the time, if the time exceeds the expiry time, log the user out, otherwise, if the expiry key is present inside your storage, keep the user logged in.

Pine answered 15/12, 2020 at 8:3 Comment(0)
B
4

Store the JWT in browser Local Storage if the user chooses the remember me option. Assuming you can change the backend JWT expiry, make the JWT expiry longer (whatever is an acceptable number of days between logins) where the user has chosen remember me.

Babysit answered 15/12, 2020 at 3:51 Comment(2)
I only can access the token because I'm working on the frontend side and there is no way to make jwt expiry login from the frontend I think. so what you mean is if the user didn't choose the remember me option then the access token is saved in the cookie and if the user chooses the remember me options I store the token in local storage. ??Fredericfrederica
Cookies would work too if they are permanent, I was referring to the difference between Session Storage (removed when you close your browser) and Local Storage (survives browser restart). But you get the gist, Local Storage for remember me Session Storage if not. You might be out of luck however if you can't change the JWT expiry at the server. Your remember me will be limited to the validity period of the JWT.Babysit
C
1

You can do this feature by creating the remember-me checkbox and making a reference for it:

const rememberCheck = useRef(null)

In this particular case I used useState to declare the credentials, because I think it's easier to set the defaultValue on my input fields just by setting them as the value on localStorage:

const [email, setEmail] = useState(localStorage.getItem("myapp-email") || "");
  const [password, setPassword] = useState(localStorage.getItem("myapp-password") || "");

And then create a function to check if it should be remembered or not:

function remember(){
        if(rememberCheck.current.checked){
          localStorage.setItem("myapp-email", email); localStorage.setItem("myapp-password", password)
        }
        else{
          localStorage.setItem("myapp-email", ""); localStorage.setItem("myapp-password", "")
        }
      }

Then use this function to increment your submit() function, check the response of your API call and if its 200 (JWT token received from backend) you call the remember() function to store your login and password on localStorage.

Note: Also remember that the "email" and "password" keys are shared between all applications, so it's nice to set a flag on it like "myapp-email" and "myapp-password".

Carrelli answered 14/5, 2023 at 20:1 Comment(0)
J
1

I prefer @Hopey One's idea.

Store the JWT in browser Local Storage if the user chooses the remember me option.

In my case, I need a token to communicate with API from time to time(But right now I don't have a token in localStorage because the user hadn't chosen the remember me option). So I used a state to keep that. Everything worked perfectly but the problem is when I refresh the page my token is null. So, I used sessionStorage to store the token when the user don't select the remember me option. This is a code sample from my useAuth custom hook file.

const [token, setToken] = useState(
  sessionStorage.getItem('token') || localStorage.getItem('token'),
);

const login = (token: string, rememberMe = false) => {
  if (rememberMe) {
    localStorage.setItem('token', token);
  } else {
    sessionStorage.setItem('token', token);
  }
  setToken(token);
};

const logout = () => {
  localStorage.removeItem('token');
  sessionStorage.removeItem('token');
  setToken(null);
};
Jacobine answered 15/5, 2023 at 14:18 Comment(0)
P
0

After a search online I was able to find this answer in this website. The site also expands on how to load it.

function setWithExpiry(key, value, expiration) {
    const now = new Date()

    // `item` is an object which contains the original value
    // as well as the time when it's supposed to expire
    const item = {
        value: value,
        expiry: now.getTime() + expiration,
    }
    localStorage.setItem(key, JSON.stringify(item))
}

You do this to set up a way to save 'RememberMe' to your local storage with some expiration time.

Purlin answered 28/8, 2021 at 17:36 Comment(1)
yeah but that can only be done in client side right ?Fredericfrederica
B
0
const [userID, setUserID] = useState(null);
const [isRemembered, setIsRemembered] = useState(false);

useEffect(() => {
  const storedID = localStorage.getItem("userID");
  const remembered = localStorage.getItem("isRemembered") === "true";
  setUserID(storedID);
  setIsRemembered(remembered);
  // If remembered, fetch token and potentially set user state
}, []);

const handleLogin = async () => {
  // ... login logic ...
  if (isRemembered) {
    localStorage.setItem("userID", userData.id); // Store user ID
  } else {
    localStorage.removeItem("userID"); // Clear stored ID
  }
};

const handleLogout = () => {
  localStorage.removeItem("userID");
  localStorage.removeItem("isRemembered");
  // ... logout logic ...
};
  1. Storage: Use localStorage for user ID and isRemembered flag (not password!).

  2. Checkbox & Storage: Add "Remember me" checkbox. Store data only if checked.

  3. Retrieval: On component mount, check for stored data.

  4. Logic:

    • If userID and isRemembered:
    • Fetch new JWT using userID from backend (backend dependent).
    • If successful, set user state to logged-in.
    • Else, proceed with normal login.

5 . Security:

  • Never store passwords in plain text.
  • Set expiration for "remember me" functionality.
  • Consider HttpOnly cookies for added security.
  1. Logout: Clear stored data on logout.
Borneol answered 26/2 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.