小编Moh*_*han的帖子

React Native 中指定的令牌无效(JWT 身份验证)

我正在尝试将 React 迁移到 React Native,因为我想在创建网站后下一步创建一个应用程序,但由于 React-Native 的某些语法似乎与典型的 React 不同。我对react-native还很陌生,所以我认为问题出在react-native处理令牌的方式上。Graphql 查询和突变似乎工作正常,但我的 jwt 令牌和身份验证似乎受到了影响。

代码


apolloClient.js

import { ApolloClient } from "@apollo/client/core";
import { InMemoryCache } from "@apollo/client/cache";
import { setContext } from "@apollo/client/link/context";
import { createUploadLink } from "apollo-upload-client";
import AsyncStorage from "@react-native-async-storage/async-storage";

const httpLink = createUploadLink({
  uri: "http://localhost:5001/graphql",
});

const authLink = setContext(async () => {
  const token = await AsyncStorage.getItem("jwtToken");
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const client = new ApolloClient({ …
Run Code Online (Sandbox Code Playgroud)

javascript authentication jwt graphql react-native

7
推荐指数
1
解决办法
1455
查看次数

使用 NextJs 保护路由/页面

我构建了一个简单的项目,通过使用 if 和 else 语句并将每个页面放入一个函数来保护网站的路由/页面withAuth(),但我不确定这是否是使用 nextjs 保护路由的最佳方法,我注意到保护路由或页面存在延迟,例如 2-3 秒长,在将访问者或未注册用户重定向到登录页面之前,他们可以看到页面的内容。

有没有办法摆脱它或使请求更快,以便未注册的用户无法查看页面的内容?nextjs框架中是否有更好的方法来保护某个路由?

代码


import { useContext, useEffect } from "react";
import { AuthContext } from "@context/auth";
import Router from "next/router";

const withAuth = (Component) => {
  const Auth = (props) => {
    const { user } = useContext(AuthContext);

    useEffect(() => {
      if (!user) Router.push("/login");
    });

    return <Component {...props} />;
  };

  return Auth;
};

export default withAuth;
Run Code Online (Sandbox Code Playgroud)

withAuth 使用示例

import React from "react";
import withAuth from "./withAuth";

function sample() {
  return …
Run Code Online (Sandbox Code Playgroud)

javascript security reactjs next.js

0
推荐指数
1
解决办法
1万
查看次数