1

Recently I'm trying to build an JWT authentication system with an admin panel to manage login-ed users for simple purpose like RESTFUL API or realtime database(Socket.io) used in both mobile or web.But there are few issue that trips me over. The status right now is i'm able to use nodejs to create a a JWT token and past it to the front end. However after that i've no idea what to do with that token in the front end. And here are the questions

  1. If i'm using React, Redux or ReactNative, is it alright to save the token in Redux status, and call it through ajax(Axios) request , if not where should it be store?
  2. If i just wanna to use it HTML instead of any kind of single page app framework, where should i store the token (local storage, cookies, window sessionStorage, anything thing else ?)
  3. I heard that session and cookies are not a good location to store the token due to they are vulnerable to different attack , how can i prevent that?
  4. This is the biggest point where i'm stuck, I've create a Form for the user to login, after pressing the login button, i'll do an ajax request to ask for a token, after the token is received, how should i save the token (according to q2) and redirect the user to a protected route by setting the header {'x-access-token': token}?
  5. if i would want to allow the user to logout, what is the proper way to do that? (just delete the token from client storage?)
  6. I found quite a lot of tutorial about creating and refreshing the token, but i cant find any tutorial about what to do after obtaining the token? are there any good recommendations that i could follow along?
  7. I know this is weird but i feel i'm missing some of the core concept on the whole authentication flow. Could anyone try to point it out according to the questions that I've asked above?

Sorry for my bad english, i've try my best to phrase it out in a correct way.

And this is my github repo for the questions https://github.com/xylops/backend

And Thank you for the time to read this

1 Answer 1

4

Storing the Token:

Use localStorage for storing the token, So even when user refreshes the page the token still be present., You can add your token to axios header so it gets passed for every request you make.

Logging out User:

  • Yes just deleting works for simple apps.
  • You should specify expiration while creating tokens and when a user logs out, store that token in Database (usually Redis)
  • Every time a user makes a request, check if the exact same token is stored in Redis, if yes this means this is a logged out user.. return proper response back to the user.
  • Run a cron job which will keep on removing expired tokens from Redis so your redis database will not have expired tokens and at the same time your app itself will reject expired tokens.

After obtaining the Token

Do what you want to do, The token will contain the information you provide, Like user id, name and other details you choose, Based on this you can show different data in the frontend and find user specific records in the backend.

You're not missing much of anything, Logging out is not easy to implement in Token based authentication, The beauty of Token Based Authentication is your app doesn't depend on cookies, sessions and you can truly make an Stateless distributed application.


Code Example

This is how i use the token with localStorage and Axios

import axios from 'axios';

const setToken = (token) => {
    // if token is provided, save it in localStorage and add it to axios header as well.
    if ( token ) {
        localStorage.token = token
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    }
    // if token is empty, just remove it from localStorage and axios..
    // set empty token when you logout the user.
    else {
        delete localStorage.token;
        delete axios.defaults.headers.common['Authorization'];
    }
}

When the application loads for the first time and on every refresh do

if ( localStorage.token ) {
    setToken( localStorage.token );
}

And to decode the token you can use, JWT

import jwt from 'jsonwebtoken';
const decodedToken = jwt.decode(localStorage.token);

Hope this helps a little.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank so much for the answer, That definitely helps. Just one more question, i notice that i could redirect the user to a protect route using link localhost:3000/dashboard?token=xxxx.xxxx.xxxx, but if i want to keep my url clean, are there any kind of way in javascript that i could redirect user to page with a token in the request to my node server?
@Xylops its always better idea to pass tokens using Headers, Anyways if you're passing token form server back to client using request parameters and if they're both on different domains (if on same domain, you can make use of localStorage) then In your frontend app, in main file (index.js) you can check if the token exists in localStorage, if not check if it exists in url parameters, If it does validate and proceed as usual otherwise show a Invalid auth token page/login page. I dont think you can pass a custom header back from server to client on re-direct.
You can additionally render login page in the client app itself, and process login using Ajax, and based on server response store token, redirect to other page within app otherwise show error to the user., Doing this you won't rely on server for generating the frontend and you can host frontend on any static host like AWS S3.
I've take the advice and pass the token through Headers. However, i realized that it is impossible to change Request Headers on client side , unless i passed it through cookies. I think i'll just use ReactJS and create a singlepage app to make api calls with custom header like what you have show me above instead of traditional page to page website. Anyway Thank you again for your patient and help :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.