0

I have two nodejs app for client and server. Client side doesn't rely on any libraries for building interfaces. It uses pure html and express routes to the requested page.

router.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

Client sends an auth request to the server via AJAX call and receive the auth token back. I need to store it somewhere and make sure express checks if token is available or not to reroute user to login page if unauthenticated (token is not available)

I was thinking to use localStorage but it is not available/accessible under express.

$.ajax({
  url: 'http://server:8080/login',
  type: "POST",
  data: {username, password},
  dataType: "JSON",
  contentType: 'application/json',
  success: function (data) {
    localStorage.setItem("jwtToken", data.jwtToken);
  },
});
likeachamp
  • 765
  • 4
  • 11
  • 21

2 Answers2

0

Maybe your should consider store it like a cookie and all the new requests to your server will contain the necessary information to verify the auth of the client.

  • I can access cookies `req.headers.cookie` in the router but how I am going to store it from AJAX response (in success)? – likeachamp Jan 25 '21 at 21:35
  • https://stackoverflow.com/questions/3340797/can-an-ajax-response-set-a-cookie#:~:text=Yes%2C%20you%20can%20set%20cookie,as%20in%20any%20HTTP%20request. – FRANCISCO CABELLO Jan 25 '21 at 22:04
  • I believe it means `success: function (data, status, xhr) {xhr.setRequestHeader('Authorization', data.token);}` but it doesn't make the value available in other requests. – likeachamp Jan 25 '21 at 22:33
  • if you set up the cookie in the browser it'll become available in every other request. Set cookie: https://developer.mozilla.org/en-US/docs/DOM/document.cookie – FRANCISCO CABELLO Jan 26 '21 at 14:56
0

So that developers don't have to deal with tokens and other aspects of an authentication system, I created an npm package. You can check if the user is logged in or not with this package as well. Here is the link:

https://www.npmjs.com/package/authenticatejs

Ryan
  • 110
  • 9
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '22 at 12:31