0

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.

1 Answers1

0

First of all after successful call to api, you need to save your token somewhere, it can be localstorage for example. You will need it to pass token to your requests and check is user authenticated. After saving token somewhere you need to make a redirect to some protected route, so the user wouldn't stay on login page.

Make sure that you also check if user authenticated on login\registration pages, so user couldn't see them when he logged in.

Here is a link about how to configure private routes in react-router-dom

Hope it helped.