I'm having a problem trying to learn authentication with JWT, cause I don't know what to do after checking the username and password with bcrypt and creating the token.
I was thinking that maybe it's because I don't understand how headers works, so I hope someone can help me with my problem.
Here's the relevant parts of my code:
Index (back-end where i'm generating the token and sending it to the front-end):
app.post('/login', (req, res) => {
usersModel.users.findOne({username: req.body.username}, (err, user) => {
if(err) {
res.json('ERRO!: ' + err)
}
else {
if(user!=null) {
bcrypt.compare(req.body.password, user.password, (err, response) => {
if(err) {
res.json('ERRO!: ' + err)
}
else {
if(response==true) {
const token = jwt.sign({
id: user._id
}, SECRET, { expiresIn: '30000'})
res.json({message: 'Passwords batem!', token})
}
if(response==false) {
res.json('Passwords não batem!')
}
}
})
}
}
})
})
Login.js:
import React from "react"
import {Link} from "react-router-dom" import { useState, useEffect } from "react";
export default function Login() {
const [username, setUsername] = useState("") const [password, setPassword] = useState("") const [listOfUsers, setListOfUsers] = useState([])
const handleSubmit = () => {
fetch('http://localhost:3001/login', {
method: 'POST', headers: {
'Content-Type': 'application/json'
}, body: JSON.stringify({username, password})
}).then((response) => response.json()).then((res) => {
console.log(res)
})
}
return (
<div className="logindiv">
<h1>Login: </h1>
<div className="inputlogindiv">
<input className="inputlogin" type="text" placeholder="Username..." onChange={(e) => {
setUsername(e.target.value)
}}></input>
<input className="inputlogin" type="text" placeholder="Password..." onChange={(e) => {
setPassword(e.target.value)
}}></input>
</div>
<br></br> <br></br>
<div className="logindivbuttons">
<button className="buttonregisterlogin" onClick={handleSubmit}>Login</button> <a href="/register"><button className="buttonregisterlogin">Register</button></a>
</div>
<br></br>
</div>
)
}
After I send the token to the front-end it shows the token and the message that the password matches, but I need to know how to acess this token or send it to the header when I fetch on the front-end to complete the authentication logic.
I have to create private routes using JWT, if someone is able to help-me, please, do it, cause I'm really having a bad time lately.