'How do I pass the JWT from the server to the client in a an http-header
No matter how hard I searched the answer, I'm not satisfied. I find everywhere explanations on how to pass the JWT Token from the client to the server as well as the most secure way to do it. However, that bugs me a bit. I want to send the client's JWT token to the latter via an HTTP header but which one? From what I understand this is the most secure way rather than using a cookie.
Assuming the user is already registered in my database. He submitted the login form to the server, I retrieved the credentials and from these, I generated a JWT. Now i am using express, how to send that JWT to the cleint in a header?
I am using express in my case
app.post("/login", async (inReq, inRes) => {
//Loadin the user's database
usersDB.loadDatabase((err)=>{
if (err) {console.log("Error while loading database: usersDB")};
});
// Our login logic starts here
//We get the user's data
const { username, password } = inReq.body;
//We validate user input in some way.
if(username.length < 4 || password.length < 8)
return inRes.status(400).send('Bad data');
//and then we try to
try {
//Check if the user exists in our database
const foundUser = await findUser(usersDB,{"username":username});
//Compare the two passwords (the one found in the DB and the one sent by our client)
if (foundUser && (await bcrypt.compare(password, foundUser.password))) {
//If evrything's fine we create token
const token = await jwt.sign(
{ user_id: foundUser._id, username },
process.env.TOKEN_KEY,
{
expiresIn: "40s",
},
function(err, intoken) {
if(err) {
console.log(err);
return inRes.status(500).json({current_view: 'error', data: err});
}
});
Now here
- WHAT TO DO WITH THE TOKEN????
- WHAT HEADER SOULD I USE ? And How?
// make a response to the user (successful login)
return inRes.status(200).json(current_view: 'home', data: user);
}
//If the user is not valid we send an error
return inRes.status(401).json(current_view: 'login', data: 'wrong-credentials');
}
//We catch and log any error
catch (err) {
console.log(err);
}
// Our register logic ends here
});
Solution 1:[1]
I'm also in the same boat at the moment; as you have probably found by now there's no authoritative consensus on how to send the JWT to the client. The only rules of thumb I've seen so far are from this link:
https://github.com/dwyl/hapi-auth-jwt2/issues/82#issuecomment-129873082
putting the JWT token in the Authorization header gives us flexibility to send an actual response in a web application. For a REST-only App/API you are free to send the JWT as the response body or a cookie. What matters is how the client stores the JWT and sends it back to the Server, which is done in the Authorization header (or Cookie or URL Token if you prefer) ?
As for this existing in the "wild", I have not seen an example of the server sending an Authorisation header to the client, but there is nothing in the spec to suggest this is an anti-pattern. see: http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html
Using Express, I've been testing sending the JWT via Authorization header:
inRes.set('Authorization', `Bearer ${myJWT}`);
Do this before setting the inRes.status.
On the client side, things seem a bit more straightforward. Everything I've read says not to store the JWT in localStorage (if that's even an option for you) as there's no expiration property. Cookies are only slightly better because they can be set to expire by date or by session, but have the bonus feature that they're sent back to the server with future requests. At that point, sessionStorage is a potential because it has a hard and fast expiration period in that they only last until the browser is closed.
You can check out this suggestion linked below (although examples are specific to Java, it's more of a general purpose explanation) for how to store the JWT on the client:
Solution 2:[2]
Thank Scopique you for your reply . Yes indeed I understood that the solution to this dilemma is not subject to consensus. Besides, while talking about that, I went through the same gitHub issue as you lol. I think that since web security is at stake, a secure approach must be included in the description of an RFC standard.
Since I'm not currently concerned with the front-end side, I didn't think about how to store my token. However, I sketched out this modest diagram.
(Note: I am not stipulating that this is the GOOD practice!). It's the best i found for now

I just hope it's not bad to do things like that. at least for a first time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Scopique |
| Solution 2 | Med Okl |
