简体   繁体   中英

Log out user when JWT has expired

After successful login I'm storing a JWT in context/localStorage. I have my auth context setup like this. How can I use the token details iat and exp to log the user out once it expires?

Also the refresh limit is hard set at 1.

export const UserContext = createContext();

export function AdminPrivateRoute({ component: Component, ...rest }) {
  const { userInfo } = useContext(UserContext);
  const { token } = useContext(TokenContext);

  /* Token details
    exp: "",
    iat: "",
    jti: "",
    refreshCount: "",
    refreshLimit: "",
    sub: "",
  */

  console.log("userInfo in AdminPrivate", userInfo);
  return (
    <Route
      {...rest}
      render={(props) =>
        userInfo.isLoggedIn ? (
          <Component {...props} />
        ) : (
            <Redirect
              to={{
                pathname: "/login",
                state: { from: props.location },
              }}
            />
          )
      }
    />
  );
}

export function UserProvider({ children }) {
  const history = useHistory();
  const [userInfo, setUserInfo] = useLocalStorage("user", {
    isLoggedIn: false,
    type: "",
    id: "",
    attributes: {
      fullName: "",
      token: "",
    },
  });

  const value = useMemo(() => ({
    userInfo, setUserInfo, logout: user => {
      setUserInfo({
        isLoggedIn: false,
        type: "",
        id: "",
        attributes: {
          fullName: "",
          token: "",
        },
      })
      history.push("/login");
    }
  }), [userInfo])

  return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

Basic routing setup

<Router>
  <ResourcesProvider>
    <UserProvider>
      <TokenProvider>
          <Switch>
            <Redirect exact path="/" to="/login" />
            <Route path="/login" component={LoginForm} />
            <AdminPrivateRoute path="/dashboard" component={Dashboard} />
          </Switch>
      </TokenProvider>
    </UserProvider>
  </ResourcesProvider>
</Router>

Like bravemaster said you normally dont need to decode a token just for the expiry time of the token.
A token can become invalid when it expires or when it gets invalidated by the auth provider.
Typically your server application should validate the token on each request. If it's invalid it should send a http 403 status to the client.
That 403 status you can handle on your client: you can either request a new auth-token with your refresh token or you can redirect the user to a login page or log out the user.

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