mongodb / stitch-js-sdk

MongoDB Stitch JavaScript SDK
Apache License 2.0
113 stars 67 forks source link

Authenticate with an API Key sample code syntax error #364

Closed hdehal closed 4 years ago

hdehal commented 4 years ago

In the "Authenticate with an API Key" example on https://docs.mongodb.com/stitch/authentication/api-key/#authenticate-with-an-api-key there is an issue with the sample code and it fails to compile:

.catch(err => console.error(`login failed with error: ${err}`); 

Should be:

.catch(err => { console.warn(`login failed with error: ${err}`); });

Having said that, once I can get it to compile with the fix above, I still get a console error which is probably unrelated -- I've imported UserApiKeyCredential and created a private and public key pair per https://docs.mongodb.com/stitch/authentication/api-key/#create-a-server-api-key -- any thoughts on if I'm missing something obvious?

const credential = new UserApiKeyCredential("<your-api-key>")
Stitch.defaultAppClient.auth.loginWithCredential(credential)
  .then(authedId => {
     console.log(`successfully logged in with id: ${authedId}`);
  })
.catch(err => { console.warn(`login failed with error: ${err}`); });

... Compiles and yields the following console error:

login failed with error: StitchServiceError: authentication via 'api-key' is unsupported

Thanks!

makesitgo commented 4 years ago

Hey @hdehal ... first off, thanks for pointing out the compile error in our documentation! Although, it looks like we are just missing a ) at the end of the .catch, wrapping the console.error call in curly braces won't be necessary. We'll get that fixed ASAP.

As for the login error, have you first initialized the Stitch app client to connect to your particular Stitch app? Check out https://docs.mongodb.com/stitch/tutorials/guides/todo-guide-1/#connect-to-stitch for details on how to connect the SDK to your app first. If you're wondering what a "Stitch app" is, then check out https://docs.mongodb.com/stitch/tutorials/guides/blog-backend/ on how to build out a simple Stitch app first.

Long story short: your error is arising from the fact that the (potentially un-) connected Stitch app does not yet support api-key authentication. My guess is you just need to call Stitch.initializeDefaultAppClient(<APP_ID>) somewhere first. And if you haven't yet created the Stitch app, do that first and configure it to support API Key authentication (https://docs.mongodb.com/stitch/authentication/api-key/#configuration).

hdehal commented 4 years ago

Thanks for the quick reply. And yes, I had already done the steps at https://docs.mongodb.com/stitch/tutorials/guides/blog-backend/ and am initializing the Stitch app client:

import { Stitch, RemoteMongoClient, AnonymousCredential, UserApiKeyCredential } from 'mongodb-stitch-browser-sdk';

// Connect to MongoDB Stitch
// Get the existing Stitch client
const stitchClient = Stitch.initializeDefaultAppClient("XXXX-YYYY");

// Get a client of the Remote Mongo Service for database access
const mongoClient = stitchClient.getServiceClient(RemoteMongoClient.factory, 'mongodb-atlas')

// Retrieve the database
const db = mongoClient.db('vendor')

// Retrieve the collection in the database
const vendorTable = db.collection('vendor-item')

Also, no other changes to my app, and all was working fine at least anonymously until an hour ago.

Previously this worked:

      // Login with anonymous credential
      stitchClient.auth
      .loginWithCredential(new AnonymousCredential())
      .then((user) => {
        console.log(`Logged in as anonymous user with id: ${user.id}`)
      })

And now neither 'AnonymousCredential' nor 'UserApiKeyCredential' seem to work, both generate the following console errors:

Object { message: "(MustAuthenticateFirst): method called requires being authenticated", name: "StitchClientError", errorCode: 1, errorCodeName: "MustAuthenticateFirst", stack: "" }

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://stitch.mongodb.com/api/client/v2.0/app/XXXX-YYYY/location. (Reason: CORS request did not succeed).

uncaught exception: Object
hdehal commented 4 years ago

Update: I realized that suddenly my PrivacyBadger extension decided to lock down my app on its own, so that was causing the CORS issue (https://www.eff.org/privacybadger).

The only error I get now is:

login failed with error: StitchServiceError: authentication via 'api-key' is unsupported

When trying the following code, after having initialized the Stitch app client:

import { Stitch, RemoteMongoClient, AnonymousCredential, UserApiKeyCredential } from 'mongodb-stitch-browser-sdk';

// Connect to MongoDB Stitch
// Get the existing Stitch client
const stitchClient = Stitch.initializeDefaultAppClient("XXXX-YYYY");

// Get a client of the Remote Mongo Service for database access
const mongoClient = stitchClient.getServiceClient(RemoteMongoClient.factory, 'mongodb-atlas')

// Retrieve the database
const db = mongoClient.db('vendor')

// Retrieve the collection in the database
const vendorTable = db.collection('vendor-item')

...

      const credential = new UserApiKeyCredential("<your-api-key>")
      Stitch.defaultAppClient.auth.loginWithCredential(credential)
        .then(authedId => {
           console.log(`successfully logged in with id: ${authedId}`);
        })
      .catch(err => { console.warn(`login failed with error: ${err}`); });
hdehal commented 4 years ago

OK, so I've redone initializing the app via the examples at https://docs.mongodb.com/stitch/tutorials/guides/todo-guide-1/#connect-to-stitch and you were correct -- it was unclear to me that the processes were going to be different for anonymous vs API logins and I couldn't merely swap in the API login method for the anonymous login method.

Feel free to close the ticket.

Thanks for the support!