简体   繁体   中英

PrivateRoute component for authentification

i am developping a Reactjs-nodejs application. I would like to make a JWT authentification. when we log in, i give a unique token to the user. Then, thanks to this token, if it is valid, i allow the user to navigate through my router. my private route component is like : PrivateRoute

My function getId is like that:

async function getId(){ let res = await axios('_/api/users/me',{config}).catch(err => { console.log(err)});

return res+1; }

Finally the config component is the token stored in the localStorage :

const config = { headers: { Authorization: ${window.localStorage.getItem("token")} } };

GetId() returns the id of the user if logged in, else it is null.

The problem now is that my privateRoute always redirect to "/" path. I think it is because of the axios(promise) that gives me the userId too late. please tell me if you understand well and if you have a solution. Thanks you

You can create private-route like this .

const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
};

then you can use

<PrivateRoute path="/" component={FIlname} />

if you are using redux, you can make the following:

in reduer:

case LOGIN_ADMIN_SUCCESS:
            localStorage.setItem("token", action.payload.token);
            return {
                ...state,
                user: action.payload,
                isSignedIn: true,
                loadingSignIn: false,
                token: action.payload.token,
            };

then in your private router you have to check these values, like

const PrivateRoute = ({ component: Component, admin, ...rest }) => (
    <Route
        {...rest}
        render={(props) => {
            if (admin.loadingSignIn) {
                return <h3>Loading...</h3>;
            } else if (!admin.isSignedIn) {
                return <Redirect to="/login" />;
            } else {
                return <Component {...props} />;
            }
        }}
    />
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM