jwt ->authentication
create jwt token -> during login,register (authentication) --> access-token and refresh-token
- jwt.sign({},<secret-key>,{ expiresIn : '2h' })
verify jwt token -> (autherization)
- jwt.verify(<token>,<secret-key>,()=>{})
access-token -> expire is given , -> no one can stole this token and use it
refresh-token -> regenerate access-token if user is valided (so that user dont be forced to be login again and again after 2h )
steps:
login generate -> access-token and refresh-token
with refresh-token we can generate ->new access-token and new refresh-token
frontend:
login -> access-token and refresh-token
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await axios.post("/login", { username, password });
setUser(res.data);
} catch (err) {
console.log(err);
}
};
const handleDelete = async (id) => {
setSuccess(false);
setError(false);
try {
await axiosJWT.delete("/users/" + id, {
headers: { authorization: "Bearer " + user.accessToken },
});
setSuccess(true);
} catch (err) {
setError(true);
}
};
refresh-token -->
automatically called using axios.interceptors
const refreshToken = async () => {
try {
const res = await axios.post("/refresh", { token: user.refreshToken });
setUser({
...user,
accessToken: res.data.accessToken,
refreshToken: res.data.refreshToken,
});
return res.data;
} catch (err) {
console.log(err);
}
};
const axiosJWT = axios.create()
axiosJWT.interceptors.request.use(
async (config) => {
let currentDate = new Date();
const decodedToken = jwt_decode(user.accessToken);
if (decodedToken.exp * 1000 < currentDate.getTime()) {
const data = await refreshToken();
config.headers["authorization"] = "Bearer " + data.accessToken;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);