【问题标题】:Problem with Authentication using Apollo and React-native使用 Apollo 和 React-native 的身份验证问题
【发布时间】:2021-10-03 05:30:22
【问题描述】:

我有这个身份验证问题

注册工作完美,服务器获取注册数据:用户密码电子邮件和号码。这一步之后,我就有了OTP验证

我得到了 pin 码并运行了验证突变。 在验证时,我得到了错误:

您未通过身份验证

所有进程都停止了,因为我没有通过验证

这里是 react-native 部分的代码

const VERIFY = gql
mutation($token: String!, $kind: TokenKind!) {
    verify(token: $token, kind: $kind)
}
const VerificationScreen: React.FC < any > = (props) => {
        const token = (props as any).route.params.token;
        const [loading, setLoading] = React.useState < boolean > (false)
        const [pin, setPin] = useState < string > ('')
        const [veryfy] = useMutation(VERIFY)
        const verifyPin = () => {
            if (!pin) {
                alert('Please TYPE Valid PIN')
                return;
            }
            //veryfy
            setLoading(true);
            veryfy({
                variables: {
                    token: pin,
                    kind: 'PHONE'
                }
            }).then(({
                data
            }) => {
                setLoading(false)
                console.log(data);
                if (data) {
                    props.navigation.navigate('Intro', {
                        token: token
                    });
                }
            }).catch((e) => {
                setLoading(false)
                console.log(e);
            })
        }

【问题讨论】:

  • 查看注册时服务器的响应,以检查您是否获得了某种会话令牌。如果为 true,那么您可能需要向 apollo 客户端添加身份验证标头
  • 你好@NigelSavage,是的,我有会话令牌。如何添加 auth 标头?

标签: react-native apollo apollo-client react-apollo apollo-server


【解决方案1】:

下面的代码是一个示例,展示了如何使用 Apollo 中间件 [1] 和上下文 [2] 在运行时或测试时添加标头(auth)。 首先我们创建一个中间件块,然后是一个内部上下文块。
在上下文块中我们可以使用下面这行添加外部参数,这是配置请求

    const { isAuth, Authorization } = headers;

可以设置一个 boolean(Auth) 以允许将令牌嵌入到 Authorization 标头中,或者可以直接传入现有的 Authorization 标头,这对于例如测试很有用。

const getClient = () => {
// create link middleware see [1] 
    const authMiddleware = new ApolloLink((operation, forward) => {

    // code block below assumes there exists an auth token in globals
    // add headers with the client context [2]
    operation.setContext(({ headers = {} }) => {
      // auth header using global token as a bearer token
      const authHeaders = {
        Authorization: global.access_token
          ? `Bearer ${global.access_token}`
          : "",
      };
      // here an Authorization header can be passed in thru the context, 
      // which can be useful, eg for testing
      const { isAuth, Authorization } = headers;
      
      // if we have an Auth.. header we can just add that and return
      if (Authorization) {
        return {
          headers: { ...publicHeaders, ...{ Authorization } },
        };
      }
      const header = isAuth
        ? { ...publicHeaders, ...authHeaders }
        : publicHeaders;

      return {
        headers: header,
      };

    });

    return forward(operation);
    }); // end create middleware

    // create the graphql endpoint [1]
    const httpLink = new HttpLink({ uri: '/graphql' });

    // create client with the middleware and return the client
    // code block below assumes there exists a globalCache
    return new ApolloClient({
    cache: globalCache,
    link: concat(authMiddleware, httpLink),
      });
}

使用

     // add/configure the appropriate headers in the context block
     // for the client
      client
      .mutate({
        mutation: <some mutation>,
        variables: <some variables>,
        context: {
          headers: {
            isAuth: false, // or true for authenticated operation
          },
        },
      })
      .then((result) => ....)
      .catch((err) => {
        console.log(....);
      }); 

在钩子中使用

   const [runMutation, { data }] =   
       useMutation(<gql>, {
        context: {
         headers: { isAuth: true },
         variables: <some vars>,
         onCompleted: (data) => callback(data),
         onError: (error) => console.error("Error ", error),
        },
      });

链接
1 middleware
2context

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 2020-10-04
    • 2018-06-22
    • 2017-07-12
    • 1970-01-01
    • 2020-11-22
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多