This is just part of web security
Some helpful code :
1. signing jwt(sending jwt from server to client)
To achieve this:
- const payload = { id: user.id, name: user.name };
let token = jwt.sign(payload, process.env.SECRET, { expiresIn: '1m' });
res.json({
accessToken: token,
message: "Logined succesfully"
}); - axios.post('http://localhost:3001/login', { name: name, password: pass })
.then(response => {
setmessage(response.data.message);
if (response.data.accessToken) {
localStorage.setItem("jwt", JSON.stringify({ token: response.data.accessToken }));
}
history.push("/");
})
.catch(error => console.error('There was an error!', error));
2. verifying jwt(sending jwt from client to server)
Method 1: work like a charm (successful or effective)
let token = localStorage.getItem("jwt");
let decodedToken = jwt_decode(token);
let currentDate = new Date();
// JWT exp is in seconds
if (decodedToken.exp * 1000 < currentDate.getTime()) {
localStorage.removeItem("jwt")
console.log("Token expired.");
return false;
} else {
console.log("Valid token");
return true;
}
Method 2:
-
function checkAuth() {
const token = JSON.parse(localStorage.getItem("jwt")).token;
const headers = {
'Authorization': token
};
axios.get('http://localhost:3001/checkauth', { headers })
.then(response => {
console.log(response);
if(response.data.message!=null)
setmessage(response.data.message);
else if(response.data.name!=null)
setmessage(response.data.name);
setTimeout(() => {
setmessage("");
}, 1000);
})
.catch(error => console.error('There was an error!', error));
} -
const token = req.headers.authorization;
if (!token) {
console.log("there is no token came from frontend");
}
else {
jwt.verify(token, process.env.SECRET, function (err, decoded) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log(decoded);
res.send(decoded);
}
});
}
3. redirecting to private page just after clicking login submit button
To achieve this:
a. import { useHistory } from 'react-router';
b. const history = useHistory();
c. history.push("/");
4. redirecting to login page just after clicking logout submit button
To achieve this:
a. import { useHistory } from 'react-router';
b. const history = useHistory();
c. history.push("/login");