0

Currently I have a backend where I am able to verify access tokens with this simple function:

const { verify } = require("jsonwebtoken");

const isAuth = req => {
  const authorization = req.headers["authorization"];
  if (!authorization) throw new Error("You need to login");

  const token = authorization.split(" ")[1]; //Bearer token123123jjjjasd , we get the token value
  const { userId } = verify(token, process.env.ACCESS_TOKEN_SECRET);
  return userId;
};

module.exports = {
  isAuth
};

But what about doing that in the front side / react to protect my routes? Isn't it dangerous to store the secret in my front end? Should i create a verification route in my backend and send there the access tokens and return true if valid, or else false? Would that be secure?

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
mouchin777
  • 1,428
  • 1
  • 31
  • 59

2 Answers2

4

You should not store JWT secret in client side. It is not secure to store it in the client side.

And you don't need the JWT secret in client side.

You can decode the token in client side using jwt-decode package.

Or if you want to decode without using a package, you can look at here.

To protect routes in React, you can create a ProtectedRoute component as described in this answer.

Also it is a best practise to generate token with a short expire time.

SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
  • So with your info ive had some toughts about it and figured the following. I must make a verification service in my backend "/verification (f.e)" , and a verification service in my frontend. Every time I login I will save my accesstoken in a cookie, then to login in each react route. I will have a react auth service, where I will send my token (grabbing it from the cookie) to the backend "verification" route, there I will check if its valid , or expired (emit a new one if expired). THen my react side auth will emit true or false based on that, and I will be able to protect the routes that way. – mouchin777 Dec 29 '19 at 18:27
  • 1
    @mouchin777 we generally save the token in localStorage when we login, and when we want to access a protected api, we read the token from localStorage, and attach it to the authorization header of the request. – SuleymanSah Dec 29 '19 at 19:12
0

I think, as you're saying, it would be better to have a route in your backend to check if the user is authorized. Because, as the documentation says, it is not secure to store api keys and such stuff in your React app.

From the create-react-app documentation:

WARNING: Do not store any secrets (such as private API keys) in your React app!

Environment variables are embedded into the build, meaning anyone can view them by inspecting your app's files.

  • You can just block the route conditionally or issue redirects using render props in React Router. You don't need to build middleware for this. – ihodonald Mar 16 '21 at 20:52