Morgan G Morgan G - 10 months ago 57
JSON Question

How do I add a json web token to each header?

So I am trying to use JSON web tokens for authentication and am struggling trying to figure out how to attach them to a header and send them on a request.

I was trying to use but I could not get it working with Angular and gave up, and figured I could just figure out how to either send the JWT in every request or send it in the header(preferably the header). It's just been a little bit harder than I thought it would be.

Here is my Login

submitLogin(username, password){
let body = {username, password};
response => {
localStorage.setItem('jwt', response);


and my login.service

return'/login', JSON.stringify(form_body), {headers: headers})
.map((response => response.json()));

I know these are not really needed but maybe it'd help! Once this token gets created and I store it, I would like to do 2 things, send it in the header and extract the expiration date that I put in with this.

Some of the Node.js login code

var jwt = require('jsonwebtoken');
function createToken(user) {
return jwt.sign(user, "SUPER-SECRET", { expiresIn: 60*5 });

Now I am just trying to pass it via an angular service back to node with this service.

headers.append('Authorization', jwt);
return this.http.get('/api/users/', {headers: headers})
.map((response => response.json().data));

JWT is my webtoken in local storage that I pass through my component to the service.

I get no errors anywhere but when it gets to my node server I never receive it in the header.

'content-type': 'application/json',
accept: '*/*',
referer: 'http://localhost:3000/',
'accept-encoding': 'gzip, deflate, sdch',
'accept-language': 'en-US,en;q=0.8',
cookie: 'connect.sid=s%3Alh2I8i7DIugrasdfatcPEEybzK8ZJla92IUvt.aTUQ9U17MBLLfZlEET9E1gXySRQYvjOE157DZuAC15I',
'if-none-match': 'W/"38b-jS9aafagadfasdhnN17vamSnTYDT6TvQ"' }

Answer Source

I'm not a NODE guy. But once, I was watching Youtube video and I feel like it might help you as it has JWT implementation not core implementation but basic.The Github Repo which he uses might help you with NODE.js.

You Tube Video for basic understanding of observables (This video has a basic implementation of JWT with NODE Api)

You can directly start watching at 14:00 if you don't like to see whole video.

Note: This video is just for understanding/learning purpose but It has a repo at Github which might help you.

Good Luck !