简体   繁体   English

当 JWT 过期时注销用户

[英]Log out user when JWT has expired

After successful login I'm storing a JWT in context/localStorage.成功登录后,我将 JWT 存储在 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?过期后如何使用令牌详细信息iatexp将用户注销?

Also the refresh limit is hard set at 1.刷新限制也硬设置为 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.如果它无效,它应该向客户端发送 http 403 状态。
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.您可以在客户端上处理的 403 状态:您可以使用刷新令牌请求新的身份验证令牌,也可以将用户重定向到登录页面或注销用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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