首页 > 解决方案 > Dialogflow 的“请求具有无效的身份验证凭据。应为 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据”

问题描述

我正在将 Dialogflow ES 聊天机器人(作为屏幕)集成到 React Native 应用程序中。在过去的几周里,我一直试图找出这个错误:

{"error":{"code":401,"message":"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.","status":"UNAUTHENTICATED"}}

console.log(JSON.stringify(result));在我的 Chat.js 中执行此操作后出现该错误。我按照本教程创建了 React Native 屏幕并尝试配置 Dialogflow:https ://blog.jscrambler.com/build-a-chatbot-with-dialogflow-and-react-native/

我按照本文档中的步骤进行 Dialogflow 设置:https ://cloud.google.com/dialogflow/es/docs/quick/setup#node.js

我创建了一个服务帐户并下载了一个密钥并将其放入我的 env.js 文件中。以下是我使用的一些命令及其结果:

C:\Users\priya\Documents\Ramitha_Projects\MTSummer2021\MTSummer2021>set GOOGLE_APPLICATION_CREDENTIALS=C:\Users\priya\Downloads\mt-bot-wkgm-7242254db130.json
C:\Users\priya\AppData\Local\Google\Cloud SDK>gcloud auth activate-service-account integrate-dialogflow@mt-bot-wkgm.iam.gserviceaccount.com --key-file=C:\Users\priya\Downloads\mt-bot-wkgm-7242254db130.json --project=mt-bot-wkgm

Activated service account credentials for: [integrate-dialogflow@mt-bot-wkgm.iam.gserviceaccount.com]

https://cloud.google.com/sdk/auth_success
C:\Users\priya\Documents\Ramitha_Projects\MTSummer2021\MTSummer2021>gcloud auth application-default print-access-token

访问令牌打印在这里,但我不会透露

C:\Users\priya\Documents\Ramitha_Projects\MTSummer2021\MTSummer2021>gcloud auth list
Credentialed Accounts

ACTIVE: *
ACCOUNT: integrate-dialogflow@mt-bot-wkgm.iam.gserviceaccount.com

ACTIVE:
ACCOUNT: motherstouchapp@gmail.com

To set the active account, run:
    $ gcloud config set account `ACCOUNT`

聊天.js

import React, { Component } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import { GiftedChat } from 'react-native-gifted-chat';
import {
    firebase,
    firebaseConfig,
    db,
    getUserDocument,
    realtime,
  } from "../../firebase/config";
  import "firebase/auth";
  import "firebase/firestore";
  import "firebase/database";
  import { dialogflowConfig } from '../../../env'; //configuration object 
  import { Dialogflow_V2 } from 'react-native-dialogflow';

  //const user = firebase.auth().currentUser;
  const MT_BOT =  {
        _id: 2,
        name: 'React Native',
        avatar:'https://www.nicepng.com/png/detail/359-3591844_svg-free-stock-african-american-women-clipart-african.png',
  };
/*
  const configureDialogFlow = (clientId = null) => {
    Dialogflow_V2.setConfiguration(
        dialogflowConfig.client_email,
        dialogflowConfig.private_key,
        Dialogflow_V2.LANG_ENGLISH_US,
        dialogflowConfig.project_id
    );
    const permanentContexts = [
      {
        name: 'Auth',
        parameters: {
          lifespanCount: 100,
          AccessToken: clientId,
        },
      },
    ];
    Dialogflow_V2.setPermanentContexts(permanentContexts);
  };*/


export default class Chat extends React.Component {

  /*  static navigationOptions = {
        title : 'Chat',
    }*/

    state = {
        messages: [ 
            {
                _id: 1,
                text: 'Hi, how can I help you?', //in the component's state, there is one message when the component is rendered intially
                createdAt: new Date(), //display current time and date in the chat UI
                user: MT_BOT
            }
        ]
    };
/*
    constructor(props) {
        super(props);
 
        Dialogflow_V2.setConfiguration(
            dialogflowConfig.client_email,
            dialogflowConfig.private_key,
            Dialogflow_V2.LANG_ENGLISH_US,
            dialogflowConfig.project_id
        );
    }*/
    
    componentDidMount() { //lifecycle method to set the configuration of Dialogflow
        Dialogflow_V2.setConfiguration (
            dialogflowConfig.client_email,
            dialogflowConfig.private_key,
            Dialogflow_V2.LANG_ENGLISH_US,
            dialogflowConfig.project_id
        );
    }

    /*componentDidMount() {
        configureDialogFlow();
    }*/

    
   

    //Gifted Chat method
    onSend(messages = []) { //once user clicks "send", their message gets stored in state variable
        this.setState(previousState => ({
            messages: GiftedChat.append(previousState.messages, messages),
        }))

        let message = messages[0].text; //"hi" actual string user sends

        Dialogflow_V2.requestQuery( //sends request to Dialogflow, w 3 parameters
            message,
            //console.log(message),
            //result => console.log("resultonsend  : " + result),
            result => this.handleGoogleResponse(result), //if response is successful handleGoogle gets triggered
            error => console.log(error) //error function if not result function
        );
    }
/*
    onQuickReply(quickReply) { 
        this.setState(previousState => ({
            messages: GiftedChat.append(previousState.messages, quickReply),
        }))

        let message = quickReply[0].value;
        Dialogflow_V2.requestQuery( //sends request to Dialogflow, w 3 parameters
            message,
            (result) => this.handleGoogleResponse(result), //if response is successful handleGoogle gets triggered
            (error) => console.log(error) //error function if not result function
        );
    }*/

    handleGoogleResponse(result) {
        
        console.log(JSON.stringify(result));

        let text = result.queryResult.fulfillmentMessages[0].text.text[0]; //extract a word from result
        this.sendBotResponse(text);
    } /*.catch(error => {
        console.log(error);
      })*/
    
    sendBotResponse(text) {
        let msg = { //create the message object
          _id: this.state.messages.length + 1,
          text, //pass the message we receive to the user
          createdAt: new Date(), //when the message is generated
          user: MT_BOT //bot sends the response to the user
        };
    
        this.setState(previousState => ({   //updates state of the App component & displays text on app
            messages: GiftedChat.append(previousState.messages, [msg])
        }));
    
    }
    

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: '#caf7e3' }}>
                <GiftedChat
                    messages={this.state.messages}
                    onSend={messages => this.onSend(messages)}
                    //onQuickReply={(quickReply) => this.onQuickReply(quickReply)}
                    user={{
                        _id: 1
                    }}
                />
            </View>
        )
    }
}

环境.js

export const dialogflowConfig = {
  "type": "service_account",
  "project_id": "mt-bot-wkgm",
  "private_key_id": "",
  "private_key": "",
  "client_email": "integrate-dialogflow@mt-bot-wkgm.iam.gserviceaccount.com",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/integrate-dialogflow%40mt-bot-wkgm.iam.gserviceaccount.com"
}

我真的很感激任何可能的帮助!

标签: react-nativeauthenticationgoogle-oauthdialogflow-esservice-accounts

解决方案


推荐阅读