1

I have done a tutorial trying to get my head around JWT tokens. I seem to have got my head around the token creation as well as using the token to allow or disallow access to a route.

This all works great using postman, but in postman I enter the token under authorization. My question is: 1. how do I send the token to the client so it is saved on that client side. 2. How does the client return the token when they try to access a route? I need to understand how this happens when NOT using postman. I am sure its pretty simple.

Do I just send

`res.header('Authorization', 'Bearer', + token);`

`res.header('Authorization', 'Bearer' + token);`

But can I send this with other stuff like a message / data etc?

Then when the user tries to access a protected route later, How do I access this header. IOW how is it stored client-side?

This is what I have thus far:

`//login route`
   `app.post('/login', async function(req, res, next) {
  const { name, password } = req.body;
  if (name && password) {
    let user = await getUser({ name: name });
    if (!user) {
      res.status(401).json({ message: 'No such user found' });
    }
    if (user.password === password) {
      // from now on we'll identify the user by the id and the id is the 
      // only personalized value that goes into our token
      let payload = { id: user.id };
      let token = jwt.sign(payload, jwtOptions.secretOrKey);
      res.json({ msg: 'ok', token: token });
    } else {
      res.status(401).json({ msg: 'Password is incorrect' });
    }
  } 
});`

`// protected route
app.get('/protected', passport.authenticate('jwt', { session: false      }), function(req, res) {
  console.log('REQUEST HEADERS ON   PROTECTED::',req.headers.authorization)
  res.json('Success! You can now see this without a token.');
});`

The console.log under protected route gives me: "REQUEST HEADERS ON PROTECTED:: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTU2NjI3NTczfQ.gAU2VzpUpXHpcgM6_n8gf7D-xLCS59tK6K2RIlIk-L4" but I gather this is because I used the authorization in postman.

Wayne
  • 283
  • 1
  • 3
  • 21
  • a good starting point https://stackoverflow.com/questions/27067251/where-to-store-jwt-in-browser-how-to-protect-against-csrf – 1565986223 May 01 '19 at 07:57

1 Answers1

2

I recently worked with jwt auth using react as my front end and hapi.js as backend. To save the token on the client side, you can use localstorage like this: You have to save this on the user login component.

localStorage.setItem('token', res.data.token);

And then, to access this token on the protected router, use this :

let token = localStorage.getItem('token');
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

I hope this may help you to solve your problem on the client side.

Afrida Anzum
  • 563
  • 4
  • 19