Answer the question
In order to leave comments, you need to log in
How to properly organize work with tokens (jwt) in react?
I use node.js + express. When authorizing, I issue an accessToken and a refreshToken to the user.
There is a middleware on the back, for the test:
const jwt = require("jsonwebtoken");
require("dotenv").config();
const { tokenValidate } = require("../helpers/validate");
function authMiddleware(req, res, next) {
const authHeader = req.get("Authorization");
if (!authHeader) {
return res.status(400).send({
status: false,
message: "Where is token ?"
});
}
const token = authHeader.replace("Bearer ", "");
let validateData = {
token: token,
secret: process.env.token_secret,
type: "access"
};
const result = tokenValidate(validateData);
console.log(result);
if (result.status && result.message.type === "access") {
next();
}
return res.send({
status: false,
message: result.message
});
}
module.exports = {
authMiddleware
};
router.post("/test", authMiddleware, (req, res) => {
res.send({
message: "trorlrlrolr"
});
});
import React from "react";
import { useContext } from "react";
import { Context } from "../../Context";
import { Redirect, Route } from "react-router-dom";
const PrivateRoute = ({ component: Component, ...rest }) => {
const { state } = useContext(Context);
return (
<Route
{...rest}
render={props =>
state.tokens &&
state.tokens.refreshToken !== "" &&
state.tokens.accessToken !== "" ? (
<Component {...props} />
) : (
<Redirect to="/login" />
)
}
/>
);
};
export default PrivateRoute;
Answer the question
In order to leave comments, you need to log in
The jwt library is included in authMiddleware but has not been used yet! Here is an example of my middle
const jwt = require('jsonwebtoken')
const c = require('config')
// проверка токена
const auth = async (req, res, next) => {
try {
const token = req.header('x-auth-token') //тут может быть любой хэдр у меня кастомный
if (!token) return res.status(401).json({ msg: 'No auth 1' })
const verified = jwt.verify(token, c.get('jwtSecret'))
if (!verified) return res.status(401).json({ msg: 'No auth 2' })
req.user = verified.id
next()
} catch (e) {
res.status(500).json({ error: e.message })
}
}
module.exports = auth
router.post('/login', async (req, res) => {
// --> проверка токена на валидность
try {
const token = req.header('x-auth-token')
if (!token) return res.json(false)
const verified = jwt.verify(token, config.get('jwtSecret'))
if (!verified) return res.json(false)
const user = await User.findById(verified.id)
if (!user) return res.json(false)
return res.json(true)
} catch (e) {
res.status(500).json({ error: e.message })
}
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question