1
1
1programmer2020-03-16 13:42:37
Node.js
1programmer, 2020-03-16 13:42:37

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
};

And the route itself:
router.post("/test", authMiddleware, (req, res) => {
  res.send({
    message: "trorlrlrolr"
  });
});


Next on the front I made a PrivateRoute:
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;

1) Where should I check the functionality of the token? If I take, for example, an interceptor and look at it, but for example, there are no requests to the back on the page, then this option does not work, right?
2) If there are requests to the back, should I check everything through the interceptor? I do not quite understand how to use it in the case of a refresh token.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2021-01-12
@PAVLIK_GYRA

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

then on the front, for example, on the authorization page and sending data and checking on the server, return the token and userInfo to the front (it is also desirable to write it to localStorage of the token: dghehgfdgnhrhwrr type) in useState and pass it to the desired element through useContext. And then whatever you want... on the desired page, you can check the token again and if it is valid, perform this or that logic.
1) only on the server there is a server key for decryption.
2) for example, I check the token the first time I access the site like this
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 })
  }
})

I have any request to the server with a header and on the server it is checked by mildware auth

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question