Skip to content

Adding "token check" function for client side usage #140

@Neta-Alon

Description

@Neta-Alon

Hey guys,

A lot of the people using node-jsonwebtoken use a JavaScript framework of some sort for client side. Using JavaScript for both server side and client side has many benefits, one of the most substantial in my eyes is the ability to use the same packages for both sides.

As of now, the server side part in node-jsonwebtoken is well taken care of - verify and sign are very useful and clear. However, I found that the client side part of the package lacks some things.

Although you can use decode to disassemble the token on the client side and store it in your own variables/store, there isn't really a very convenient way to check if a token is valid. By valid I don't mean it's signature, obviously, but it's integrity and expiration time.

There isn't really a reason to send a request to server to check if it's expired, when it's mentioned inside the token. Also, if the Base64 encoding is broken (decoded string doesn't parse to JSON) there's no point in checking it with the server, just switch to the login page and get a new token.

TL:DR -
I'm suggesting adding a check function that will be mainly directed to client side usage.

Example:

//AuthService.js
import jwt from 'jsonwebtoken';
import History from './history';

function checkAuth() {
  var token = localStorage.getItem('token');
  jwt.check(token, function callback (isValid, err) {
    if (isValid) // "Log in" to system, e.g. with flux
      LoginActions.LoginSuccess(token);
    else { // Check what's wrong using err, redirect to login page and show user appropriate message
      History.pushState(null, '/login');
      if (err === "TokenExpired")
        LoginActions.LoginFailed("Authentication expired. Please log in again");
      if (err === "TokenMalformed")
        LoginActions.LoginFailed("Something broke. Please log in again");
    }
  });
}

Then you can just import Auth from './AuthService.js' and check the token in the application main loading point - In React, for example, it would be before ReactDOM.render(<Router history={history}>{routes}</Router>, document.getElementById('app'));.

I believe such a function would be useful and could save http requests and provide a very clear abstraction for a common use with tokens.

Thanks for taking the time to read this!
Neta

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions