I have been searching for an answer on how to pass the JWT Token from the client to the server securely, but I am not satisfied with the explanations I found. Everyone talks about the most secure way to transfer the JWT token using HTTP headers instead of cookies. But I am still confused - which specific header should I use to send the client's JWT token?
Let's say a user is already registered in my database and has submitted their login credentials to the server. After retrieving the credentials, I generated a JWT based on that information. Now, I am working with Express - can someone guide me on how to send this JWT to the client using a header?
I am implementing this using Express
app.post("/login", async (inReq, inRes) => {
//Loading the user's database
usersDB.loadDatabase((err)=>{
if (err) {console.log("Error while loading database: usersDB")};
});
// Starting our login logic here
//Fetching the user's data
const { username, password } = inReq.body;
//Validating user input in some way.
if(username.length < 4 || password.length < 8)
return inRes.status(400).send('Bad data');
//then attempting to...
try {
//Checking if the user exists in our database
const foundUser = await findUser(usersDB,{"username":username});
//Comparing the passwords (the one from DB and the one sent by the client)
if (foundUser && (await bcrypt.compare(password, foundUser.password))) {
//Creating a token if everything checks out
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 what?
- WHAT DO I DO WITH THE TOKEN????
- WHICH HEADER SHOULD I USE? And How?
//sending a response to the user (successful login)
return inRes.status(200).json(current_view: 'home', data: user);
}
//Sending an error message if the user is not valid
return inRes.status(401).json(current_view: 'login', data: 'wrong-credentials');
}
//Catching and logging any errors
catch (err) {
console.log(err);
}
// Finishing our register logic
});