使用 Apollo 和 React-native 的身份验证问题

问题描述

我有这个身份验证问题

注册完美服务器获取注册数据 用户密码邮箱和号码 这一步后,我有OTP验证

我获得了 PIN 码并运行了验证突变。 在验证时,我收到错误

您未通过身份验证

所有过程都停止了,因为我没有得到验证

这里是 react-native 部分的代码

const VERIFY = gql

mutation($token: String!,$kind: TokenKind!) { 验证(令牌:$token,种类:$kind) } const VerificationScreen: React.FC = (props) => {

const token = (props as any).route.params.token;

const [loading,setLoading] = React.useState(false)

const [pin,setPin] = useState('')

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);
  })

}

提前致谢

解决方法

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
2 context