Do I need to verify JWT token in PrivateRoutes component if I use redux and redux persist? (with local storage)

huangapple go评论87阅读模式
英文:

Do I need to verify JWT token in PrivateRoutes component if I use redux and redux persist? (with local storage)

问题

我有一个社交媒体应用程序。令牌在用户登录时被发放(显然)。我需要在允许访问私有路由之前将令牌发送到后端以进行验证吗?

如果确实需要验证令牌,下面的方法是否正确?在这里是否可以使用本地身份验证状态而不是存储在redux存储中的状态?(抱歉,我是新手认证用户)。另外,如果用户通过令牌验证并进入了动态页,例如在"/people"页面上获取所有其他用户时,我是否需要验证用户的令牌?还是因为令牌在每次重新加载时在PrivateRoutes组件中都会被检查,我可以在此路由中摆脱"verifyJWT"?谢谢!

const PrivateRoutes = () => {
   const navigate = useNavigate();
   let token = useSelector((state) => state.token);
   const dispatch = useDispatch();

   const [auth, setAuth] = useState(false);
   const [isLoading, setIsLoading] = useState(true);

   useEffect(() => {
      if (token) {
         const url = import.meta.env.VITE_API_URL + "auth/protected";

         axios.get(url, { headers: { Authorization: token } })
            .then(response => {
               if (response.status === 200) {
                  setAuth(true);
               }
            })
            .then(() => {
               setIsLoading(false);
            })
            .catch((err) => {
               dispatch(setLogout()); // 设置令牌和用户状态为空,授权状态也为false
               //(授权redux状态用于确定应加载哪种标题)

               setAuth(false);
               setIsLoading(false);
               console.log(err)
            })

      } else {
         navigate("/auth/login");
      }
   }, [])

   if (isLoading) {
      return (
         <div>Loading</div>
      )
   }

   return (
      auth ? <Outlet/> : <Navigate to="/auth/login" />
   )
}

Note: 请注意,此代码中使用了一些Redux和React Router的功能,这些功能在上下文中起到关键作用,以及对Axios和useState的使用。这是一个用于身份验证的前端路由组件示例。

英文:

I have a social media application. The token is being issued whenever user logs in (obviously).
Do I need to send the token to the backend to verify it before letting an access to Private Routes?

const PrivateRoutes = () =&gt; {
   let token = useSelector((state) =&gt; state.token);

   return(
     token ? &lt;Outlet/&gt; : &lt;Navigate to=&quot;/auth/login&quot; /&gt;
   )

} 

If I in fact do need to verify the token, is the approach below correct? Is it ok to use local auth state here instead of the one that is in a redux store? (Sorry I am new to user authentication). Also, if user got through the token verification and got to the feed page, do I need to verify the token of the user when fetching for example all other users on "/people" page? Or would it be redundant since the token is checked in PrivateRoutes component on every reload and I can get rid of "verifyJWT" in this route: router.get("/", verifyJWT, getAllUsers);
Thank you!

const PrivateRoutes = () =&gt; {
   const navigate = useNavigate();
   let token = useSelector((state) =&gt; state.token);
   const dispatch = useDispatch();

   const [auth, setAuth] = useState(false);
   const [isLoading, setIsLoading] = useState(true);


   useEffect(() =&gt; {
      if(token) {
         const url = import.meta.env.VITE_API_URL + &quot;auth/protected&quot;;

         axios.get(url, {headers: {Authorization: token}})
            .then(response =&gt; {
               if(response.status === 200){
                  setAuth(true);
               }
            })
            .then(() =&gt; {
               setIsLoading(false);
            })
            .catch((err) =&gt; {
               dispatch(setLogout()); //sets token and user states to null as well as authorized to false 
               //(authorized redux state is used to determine what kind of headr should be loaded)

               setAuth(false);
               setIsLoading(false);
               console.log(err)
            })
         
      }else{
         navigate(&quot;/auth/login&quot;);
      }
   }, [])


   if(isLoading) {
      return (
         &lt;div&gt;Loading&lt;/div&gt;
      )
   }

   return(
     auth ? &lt;Outlet/&gt; : &lt;Navigate to=&quot;/auth/login&quot; /&gt;
   )

} 

答案1

得分: 0

你总是希望在发送需要用户进行身份验证的路由请求时验证令牌是否有效(这意味着用户可以被授权执行某项操作),这意味着你总是会从前端发送它并在后端解码。

对于许多请求,您需要检查用户是否有权执行某些操作,例如删除评论或帖子等。

至于将令牌发送到每个请求中,由于您正在使用axios,您可以预先配置它以发送令牌。这是通过请求拦截器完成的。

您可以在用户登录时设置拦截器,或者如果您已经存储了令牌以保持连接,可以在用户访问页面时设置拦截器。

您可以在这里查看详细信息:https://axios-http.com/docs/interceptors

英文:

You always want to verify if the token is valid (which means the user can be authorized to perform an action) when sending request to access a route that would need a user to be authenticated, which means you will always send it from the front and decode it in the back.

For a lot of requests you need to check if the user has the right to do something, like deleting a comment or a post for example.

As for the token being sent into each request, as you are using axios, you can preconfigure it so that the token is sent. It is done via request interceptors.

You set the interceptor once, either when the user logs in, either when he arrives on the page if you have stored your token in order to persist connection.

You can have a look here: https://axios-http.com/docs/interceptors

huangapple
  • 本文由 发表于 2023年7月10日 20:03:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定