nodejs-dialogflow icon indicating copy to clipboard operation
nodejs-dialogflow copied to clipboard

You need to pass auth instance to gRPC-fallback client. Use OAuth2Client from google-auth-library

Open gabrielgouv opened this issue 7 years ago • 39 comments

I dont know if it is a bug or not, but I'm trying to use the Dialogflow lib in a existing Vue project and I can't use because I always receive this error:

You need to pass auth instance to gRPC-fallback client. Use OAuth2Client from google-auth-library

I created a new Node.js project from scratch and copy and paste the exactly same code (and key) that I used in my Vue project and it works fine, but in my Vue project it does not work.

I tried to use the google-auth-library to authenticate, but no success.

This is my code:

      async detectTextIntent(text, sessionId, languageCode) {

        const sessionClient = new dialogflow.SessionsClient(this.config)
        
        const sessionPath = sessionClient.sessionPath(this.config.projectId, sessionId);
        
        const request = {
            session: sessionPath,
            queryInput: {
                text: {
                    text: text,
                    languageCode,
                },
            },
        };
        
        return await sessionClient.detectIntent(request);

    }

The config object is the credentials (I've tried using file key path and ENV variable also):

    const config = {
        projectId: "myprojectid",
        credentials: {
          private_key: "-----BEGIN PRIVATE KEY-----\n[...]\n-----END PRIVATE KEY-----\n",
          client_email: "[email protected]"
        }
      }

I dont know if can be a conflict with an existing lib.

gabrielgouv avatar Aug 14 '19 16:08 gabrielgouv

@gabrielgouv what approach does Vue use for bundling JavaScript for client side libraries? At this time most of our libraries don't have officially have browser support (see the discussion here.

We are however making strides towards adding support ... in the short term, it might be better to write a server layer that your view component interacts with, that in turn calls the dialogflow API.

bcoe avatar Aug 19 '19 20:08 bcoe

@gabrielgouv As @bcoe said, the browser support is half way there. It's already in one of the middleware libraries (google-gax), it's why you see the warning, but it's not yet in the library code- I'm going to merge some more changes this week and it will likely start working (in a limited fashion, with no streaming available - more on that in the release notes). You'll definitely need to change your auth workflow though.

Let's leave this open for now and I'll get back to this issue when more library changes are merged. But if you need to have a complete support with service accounts, consider using the backend server as @bcoe suggested.

alexander-fenster avatar Aug 19 '19 22:08 alexander-fenster

@bcoe, @alexander-fenster I understand, at the moment I chose to use the REST API, since I didn't have much time. Via REST I can communicate with Dialogflow normally.

gabrielgouv avatar Aug 20 '19 17:08 gabrielgouv

@gabrielgouv thanks for your patience :+1: we intend to make browser support better over time.

bcoe avatar Aug 20 '19 18:08 bcoe

@bcoe Hello! I am having the same issue...

You need to pass auth instance to use gRPC-fallback client in browser. Use OAuth2Client from google-auth-library.

I am referencing the Cloud AutoML: Node.js Client documentation. The error arises when I create the client for prediction service...'const client = new automl.PredictionServiceClient();' I would appreciate any guidance on how to resolve this issue.

Referenced Documentation: https://googleapis.dev/nodejs/automl/latest/index.html

RyanF18 avatar Sep 04 '19 23:09 RyanF18

@RyanF18 Are you trying to use the library in the browser, Electron app, or something like that?

alexander-fenster avatar Sep 05 '19 01:09 alexander-fenster

@alexander-fenster I just got it working but thank you for the response!

RyanF18 avatar Sep 05 '19 23:09 RyanF18

hi is there any resolution to the first error by gabrielgou? i have the same issue and not sure what to do. do you have a recipe to get around the issue?

ushypocrites avatar Sep 09 '19 23:09 ushypocrites

@gabrielgouv what approach does Vue use for bundling JavaScript for client side libraries? At this time most of our libraries don't have officially have browser support (see the discussion here.

We are however making strides towards adding support ... in the short term, it might be better to write a server layer that your view component interacts with, that in turn calls the dialogflow API.

The link doesn't lead to anymore, can you post a recipe on how to make dialogflow v2 work for browsers? Thanks.

ushypocrites avatar Sep 09 '19 23:09 ushypocrites

Hey folks @ushypocrites @gabrielgouv,

TL;DR: this library is supposed to be used from a server-side Node.js application, not from any front-end environment such as a browser, Electron app, React, (name your front-end framework here). If you just run the code by plain regular Node.js, it will work.

Having said that - we do have experimental support for a browser use case starting from the latest version, which is 0.11.0. It's experimental (just implemented) and not really documented yet. You can try using it though. To do that, you need to pass an authenticated instance of OAuth2Client (from google-auth-library) as an auth parameter of the client constructor:

const auth = require('google-auth-library');
const oauth2client = new auth.OAuth2Client(client_id, client_secret, callback_uri);
const authUrl = oauth2client.generateAuthUrl({
  access_type: 'offline',
  scope: [    // scopes for Dialogflow
    'https://www.googleapis.com/auth/cloud-platform',
    'https://www.googleapis.com/auth/dialogflow'
  ]
});
// redirect user to authUrl and wait for them coming back to callback_uri

// in callback_uri handler, get the auth code from query string and obtain a token:
const tokenResponse = await oauth2client.getToken(code);
oauth2client.setCredentials(tokenResponse.tokens);

// now use this oauth2client!
const sessionClient = new dialogflow.SessionsClient({ auth: oauth2client }); // <-- auth passed here

Since it all was baked just recently, we don't have any published documentation on that. If you folks explain your use cases (at least, what kind of environment are you targeting - is it Electron, or a regular browser, or whatever else), I might be able to provide more specific example.

But - back to TL;DR - the officially supported and easiest way to use this client library is to use it with Node.js on the server side.

alexander-fenster avatar Sep 10 '19 00:09 alexander-fenster

Hey folks @ushypocrites @gabrielgouv,

TL;DR: this library is supposed to be used from a server-side Node.js application, not from any front-end environment such as a browser, Electron app, React, (name your front-end framework here). If you just run the code by plain regular Node.js, it will work.

Having said that - we do have experimental support for a browser use case starting from the latest version, which is 0.11.0. It's experimental (just implemented) and not really documented yet. You can try using it though. To do that, you need to pass an authenticated instance of OAuth2Client (from google-auth-library) as an auth parameter of the client constructor:

const auth = require('google-auth-library');
const oauth2client = new auth.OAuth2Client(client_id, client_secret, callback_uri);
const authUrl = oauth2client.generateAuthUrl({
  access_type: 'offline',
  scope: [    // scopes for Dialogflow
    'https://www.googleapis.com/auth/cloud-platform',
    'https://www.googleapis.com/auth/dialogflow'
  ]
});
// redirect user to authUrl and wait for them coming back to callback_uri

// in callback_uri handler, get the auth code from query string and obtain a token:
const tokenResponse = await oauth2client.getToken(code);
oauth2client.setCredentials(tokenResponse.tokens);

// now use this oauth2client!
const sessionClient = new dialogflow.SessionsClient({ auth: oauth2client }); // <-- auth passed here

Since it all was baked just recently, we don't have any published documentation on that. If you folks explain your use cases (at least, what kind of environment are you targeting - is it Electron, or a regular browser, or whatever else), I might be able to provide more specific example.

But - back to TL;DR - the officially supported and easiest way to use this client library is to use it with Node.js on the server side.

@alexander-fenster Thanks so much for this! I will give it a try. The use case is a chat window in a react js website (not app) on a regular browser. I do see a few websites that have a chat UI and use dialogflow so i am wondering how they are able to do this.

ushypocrites avatar Sep 10 '19 15:09 ushypocrites

@ushypocrites There are at least five options how they can do it!

  1. As above (I bet nobody uses it this way as for now since it was released just yesterday and not yet documented, other than in this issue :) )

  2. They might use server side (backend) script. That's probably the easiest option.

  3. They might use our other library, googleapis. It supports dialogflow and is webpackable as described here. It's a little bit less fancy than this one though.

  4. They might use Google JavaScript API using the discovery document.

  5. Finally, they might be using JSON requests directly (again, this link).

My personal opinion here is that the easiest way is probably to have a backend (option 2), which probably gives you a lot of extra benefits compared to in-browser solution. Out of other four solutions, I'd prefer 1, 3, 4, 5, in this order.

alexander-fenster avatar Sep 10 '19 16:09 alexander-fenster

@ushypocrites There are at least five options how they can do it!

  1. As above (I bet nobody uses it this way as for now since it was released just yesterday and not yet documented, other than in this issue :) )
  2. They might use server side (backend) script. That's probably the easiest option.
  3. They might use our other library, googleapis. It supports dialogflow and is webpackable as described here. It's a little bit less fancy than this one though.
  4. They might use Google JavaScript API using the discovery document.
  5. Finally, they might be using JSON requests directly (again, this link).

My personal opinion here is that the easiest way is probably to have a backend (option 2), which probably gives you a lot of extra benefits compared to in-browser solution. Out of other four solutions, I'd prefer 1, 3, 4, 5, in this order.

Thanks so much! That's very useful. I am now considering 2) and perhaps using firebase. Do you have any comments about firebase? does the conversation context and intent get lost if there are long pauses between requests?

ushypocrites avatar Sep 10 '19 18:09 ushypocrites

Hey folks @ushypocrites @gabrielgouv,

TL;DR: this library is supposed to be used from a server-side Node.js application, not from any front-end environment such as a browser, Electron app, React, (name your front-end framework here). If you just run the code by plain regular Node.js, it will work.

Having said that - we do have experimental support for a browser use case starting from the latest version, which is 0.11.0. It's experimental (just implemented) and not really documented yet. You can try using it though. To do that, you need to pass an authenticated instance of OAuth2Client (from google-auth-library) as an auth parameter of the client constructor:

const auth = require('google-auth-library');
const oauth2client = new auth.OAuth2Client(client_id, client_secret, callback_uri);
const authUrl = oauth2client.generateAuthUrl({
  access_type: 'offline',
  scope: [    // scopes for Dialogflow
    'https://www.googleapis.com/auth/cloud-platform',
    'https://www.googleapis.com/auth/dialogflow'
  ]
});
// redirect user to authUrl and wait for them coming back to callback_uri

// in callback_uri handler, get the auth code from query string and obtain a token:
const tokenResponse = await oauth2client.getToken(code);
oauth2client.setCredentials(tokenResponse.tokens);

// now use this oauth2client!
const sessionClient = new dialogflow.SessionsClient({ auth: oauth2client }); // <-- auth passed here

Since it all was baked just recently, we don't have any published documentation on that. If you folks explain your use cases (at least, what kind of environment are you targeting - is it Electron, or a regular browser, or whatever else), I might be able to provide more specific example.

But - back to TL;DR - the officially supported and easiest way to use this client library is to use it with Node.js on the server side.

Nice. I will try to use later. Im currently transitioning my current front end code (which used the REST API) to my back end.

gabrielgouv avatar Sep 10 '19 18:09 gabrielgouv

@ushypocrites Firebase (cloud functions) is totally fine, and this library will work in cloud functions.

As for losing the context and intent because of the long pause, I unfortunately don't know the details of the specific API (I do work on client libraries in general, not the particular Dialogflow API). This doc has some information about context lifespans though :)

alexander-fenster avatar Sep 10 '19 18:09 alexander-fenster

@ushypocrites Firebase (cloud functions) is totally fine, and this library will work in cloud functions.

As for losing the context and intent because of the long pause, I unfortunately don't know the details of the specific API (I do work on client libraries in general, not the particular Dialogflow API). This doc has some information about context lifespans though :)

Thank you!

ushypocrites avatar Sep 11 '19 13:09 ushypocrites

@alexander-fenster thank you for explaining this in such depth! Very nice to understand why something doesn't work after a day of trying to make it work.

It may be useful to put a note in the docs that the support for browsers is not available :)

urosran avatar Oct 20 '19 06:10 urosran

@urosran ...it now works with browsers :) Unfortunately, no docs and samples yet, so we don't advertise it until we have everything ready. Long story short, as I wrote above, create an instance of OAuth2Client from google-auth-library, pass it to the client constructor, and it will work in browser.

If you tell me a little bit more about your use case (if it's an Electron app, or web page, or something else) I might be able to provide some code hints for you.

alexander-fenster avatar Oct 20 '19 19:10 alexander-fenster

I had similar issue connecting Firestore, im trying to connect with service account from client side(browser) runs on nodejs, here is the code snippet

const admin = require('firebase-admin');

var serviceAccount = require('./../key.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

var db = admin.firestore();

db.collection('xxxxx').get()
            .then((snapshot) => {
                
            })
            .catch((err) => {
                console.log('Error getting documents', err);
            });

i have got below error Uncaught (in promise) Error: {"clientConfig":{},"port":443,"servicePath":"firestore.googleapis.com","credentials":{"private_key":"-----BEGIN PRIVATE KEY-----\nMIIEvgIB......X\n-----END PRIVATE KEY-----\n","client_email":"xxxxiam.gserviceaccount.com"},"projectId":"xxxxx","firebaseVersion":"8.6.0","libName":"gccl","libVersion":"2.4.0 fire/8.6.0","scopes":["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/datastore"]}You need to pass auth instance to use gRPC-fallback client in browser. Use OAuth2Client from google-auth-library.

couldn't figured out the reason behind, can you please help me.

ghost avatar Oct 22 '19 05:10 ghost

Hi @alexander-fenster, thanks so much for your help so far. I am trying to get dialogflow to work on my react app. I was able to authenticate thanks to the steps you provided above, however, I come across an issue with CORS shown below.

Screen Shot 2019-10-31 at 5 51 50 PM

I have tried setting Access-Control-Allow-Credentials to true within gaxios.

My detectIntent function is shown below: Screen Shot 2019-10-31 at 5 54 41 PM

ajimen94 avatar Nov 01 '19 00:11 ajimen94