Reputation: 309
I'm trying to create a login and authentication system using Node.js. I'm going about it this way:
1) The users sends his credentials using a form via the POST method
2) The server checks these credentials against the database
3) If the credentials seem correct the server generates a jwt token and returns this to the user.
4) From now on the user always places this token in his http authentication header, or at least when trying to access restricted pages
5) When a user tries to access a restricted page, the server extracts the token and validates it before continuing.
Right now where i'm a bit stuck is step 4. I'd like to still be able to define my links in the typical
<a href="/restricted">Click here</a>
kind of way, but make it so that the token is actually passed in the http header. Is this possible?
So this is not about api calls, but requesting full webpages that require you to authenticate yourself with a token. So i think ajax is not appropriate here.
Upvotes: 1
Views: 251
Reputation: 6836
Basically, you cannot set headers with plain HTML. To do that, you need to send requests using XHR. On the other hand, you may want to consider adding query tag into your href link.
First, write token by using localStorage
localStorage.setItem('jsonwebtoken', 'AsdL6-4GffsdXCvS3j');
Read token and add it into your <a href>
as a query parameter ?token
<a href="/restricted?token=${localStorage.getItem('jsonwebtoken')}">Click here</a>
And then modify your server to accept token
that sent with req.query
const token = req.query.token || req.headers['X-Access-Token'];
Upvotes: 1
Reputation: 54
Unfortunately, I don't think there's a way to add your JWT token to the header, outside of using XHR or File API.
Upvotes: 0