Skip to content

Query in Parse Cloud returns "unauthorized" error #356

Description

@leonardojobim

The command query.find always returns error in Parse Cloud. The response is Response Body : {"code":141,"error":"Error: undefined unauthorized"}.
The request is being done by Swift SDK.
It looks that Parse Cloud can't access the classes of Parse Server.

What could be possible reasons ?

Parse.Cloud.beforeSave("Message", function(request, response) {
    if (!request.object.get("uniqueCode")) {
        response.error('A Message must have a uniqueCode.');
    } else {
        var Message = Parse.Object.extend("Message");
        var query = new Parse.Query(Message);
        query.equalTo("uniqueCode", request.object.get("uniqueCode"));
        query.find({
            success: function(results) {
                if (results.length > 0) {
                    response.success();
                } else {
                    response.error("A Message with this uniqueCode already exists.");
                }
            },
            error: function(error) {
                response.error("Error: " + error.code + " " + error.message);
            }
        });
    }
});

Activity

  1. gfosco commented on Feb 11, 2016

    @gfosco
    Contributor

    Are you requiring/defining Parse in your cloud code file? This should not be done, as it is a global we mutate during ParseServer initialization.

  2. leonardojobim commented on Feb 11, 2016

    @leonardojobim
    Author

    No, I am not. The code above is exactly the cloud/main.js file.

  3. gfosco commented on Feb 11, 2016

    @gfosco
    Contributor

    Are you setting any client keys in the ParseServer initialization? (rest, js, client, dotnet)... If so, remove them.

  4. leonardojobim commented on Feb 11, 2016

    @leonardojobim
    Author

    My settings is according to the Parse Server example:
    It is hosted in Heroku and the env vars below are configured.

    var databaseUri = process.env.DATABASE_URI || process.env.MONGOLAB_URI;
    
    var api = new ParseServer({
      databaseURI: databaseUri || 'mongodb://localhost:27017/dev',
      cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
      appId: process.env.APP_ID || 'myAppId',
      masterKey: process.env.MASTER_KEY || '',
      clientKey: process.env.CLIENT_KEY || ''
    });
    

    If I remove the keys ( var api = new ParseServer() ), will the server still work and will it be able to be accessed by mobile SDK ???
    The request to insert a new message (that triggers the beforeSave()) is done by Swift SDK.

  5. simonbengtsson commented on Feb 11, 2016

    @simonbengtsson
    Contributor

    I think I have the same problem as @Leo-One. I can't use any queries in cloud code using the parse server as they return with the error {"code":141,"error":"Error: undefined unauthorized"}.

    When diving into the source to troubleshoot I saw that all the queries (find, first, get etc) results in node_modules/parse-server/node_modules/parse/lib/node/RESTController.js:ajax() sending a post request to https://api.parse.com/1/classes/MyObject which of course will result in unauthorized as parse doesn't know anything about my local app. I tried sending a get request to http://localhost:1337/parse/classes/MyObject which works and returns objects as expected.

    I'm probably missing something here, but what would you have to do to get queries working in cloud code with a local parse server?

  6. simonbengtsson commented on Feb 12, 2016

    @simonbengtsson
    Contributor

    What I missed was the serverURL option. Is it the same for you @Leo-One? For me the following works perfectly for local development:

    app.use('/parse', new ParseServer({
        databaseURI: process.env.MONGOLAB_URI || 'mongodb://localhost:27017/myApp',
        cloud: __dirname + '/cloud/main.js',
        appId: 'myAppId',
        masterKey: 'tmp_master_key',
        serverURL: 'http://localhost:1337/parse'
    }));
  7. leonardojobim commented on Feb 12, 2016

    @leonardojobim
    Author

    @simonbengtsson Just out of curiosity, what is the hosting solution are you using ?

    I am using Heroku and I tried:
    serverURL: 'https://localhost:1337/parse' or
    serverURL: 'http://localhost:1337/parse' or serverURL: 'https://localhost:' + port + '/parse'-> received {"code":141,"error":"Error: 100 XMLHttpRequest failed: \"Unable to connect to the Parse API\""}

    serverURL: 'http://localhost:' + port + '/parse'-> received {"code":141,"error":"Error: undefined unauthorized"}

    None of above ones worked.

  8. leonardojobim commented on Feb 12, 2016

    @leonardojobim
    Author

    I've written the command line:

    Parse.Cloud.beforeSave("Message", function(request, response) {
        console.log('Parse.serverURL: ' + Parse.serverURL);
        if (!request.object.get("uniqueCode")) {
        //more code

    and it printed app[web.1]: Parse.serverURL: http://localhost:30835/parse in Heroku as expected.

    What more could be wrong ?

  9. simonbengtsson commented on Feb 12, 2016

    @simonbengtsson
    Contributor

    Im using the parse server locally. The serverurl for heroku would be something like http://your-heroku-app-id.herokuapp.com/parse. Or simply where the parse server is located.

  10. tanmays commented on Feb 12, 2016

    @tanmays

    Along with setting the serverURL in index.js make sure you are also passing a valid sessionToken otherwise it will throw an unauthorized error.

  11. jamiechapman commented on Feb 12, 2016

    @jamiechapman

    Also getting a similar response (141 / unauthorised) via Cloud Code. App ID matches client-side and in the ParseServer constructor + client keys not defined in client/server. Locally regular CloudCode functions (like the default hello function in parse-server-example) work just fine, it seems to be queries that have issues. Both all fail when deployed to heroku.

    client side JS:

    Parse.initialize("the_app_id", ""); 
    Parse.serverURL = "/parse";
    ...
    Parse.Cloud.run("validateEmail", {email:"..."}, {});
    ...
    

    =>

    cloud/main.js:

    Parse.Cloud.define('validateEmail', function(req, res) {
    
        // Get the email address of the user we are going to check
        var email = req.params.email;
    
        // Execute query with Parse
        var query = new Parse.Query("ObjectTest");
        query.equalTo('email', email);
        query.find({
            success: function(result) {
                res.success(result);
            },
            error: function(err) {
                res.error(err);
            }
        });
    });
    

    (nothing declared outside of Parse.Cloud.define, Parse not re-imported etc)

    => {"code":141,"error":{"message":"unauthorized"}}

  12. simonbengtsson commented on Feb 12, 2016

    @simonbengtsson
    Contributor

    What is your initialization code for the parse server @jamiechapman? Make sure you are using the serverURL option there as well.

  13. jamiechapman commented on Feb 12, 2016

    @jamiechapman

    @simonbengtsson

    The serverURL is defined and matches that defined by the client. I have tried fully qualified URL's in the client-side (http://www etc) and a relative path, both produce error 141 for some odd reason!

    var api = new ParseServer({
        databaseURI: databaseUri || 'mongodb://XXXXXXX',
        cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
        appId: process.env.APP_ID || 'XXXXXXX',
        masterKey: process.env.MASTER_KEY || 'XXXXXXX',
        clientKey: process.env.CLIENT_KEY || '',
        serverURL: 'http://www.XXXXXXX.com/parse'
    });
    

    (XXXXXXX's subbed in place of real values, both match server/client side)

  14. jamiechapman commented on Feb 12, 2016

    @jamiechapman

    @simonbengtsson Think I sussed it! The environment variable APP_ID had an extra character at the end which likely caused the requests to (rightly) fail. Thanks for the help! 👍

  15. 45 remaining items

  16. eustache509 commented on Mar 25, 2016

    @eustache509

    PLEASE LET ME KNOW HOW I CAN FIX THIS BECAUSE I SPEND 4 DAYS IN IT . I CANT FIX IT

  17. gfosco commented on Mar 25, 2016

    @gfosco
    Contributor

    You're explicitly setting the client key to a null value in that code..
    Change it to literally any string like 'clientKeyIsNotUsed' and it should
    stop telling you that.

    On Thursday, March 24, 2016, eustache509 [email protected] wrote:

    PLEASE LET ME KNOW HOW I CAN FIX THIS BECAUSE I SPEND 4 DAYS IN IT . I
    CANT FIX IT

    —
    You are receiving this because you were mentioned.
    Reply to this email directly or view it on GitHub
    #356 (comment)

  18. eustache509 commented on Mar 25, 2016

    @eustache509

    Thanks Fosco but it save still fail

  19. eustache509 commented on Mar 25, 2016

    @eustache509

    03-24 21:23:40.048 4014-4628/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:23:40.290 4014-4633/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:23:41.707 4014-4634/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:23:44.327 4014-4636/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:23:49.207 4014-4639/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:23:58.707 4014-4642/? W/System: Ignoring header X-Parse-Client-Key because its value was null.
    03-24 21:34:19.855 4698-4698/? I/Parse: Save Failed
    03-24 21:36:16.718 4791-4791/? I/Parse: Save Failed

  20. eustache509 commented on Mar 25, 2016

    @eustache509

    @OverRide
    public void onCreate() {
    super.onCreate();

    // Enable Local Datastore.
    Parse.enableLocalDatastore(this);
    
    // Add your initialization code here
    Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
                    .applicationId("verokiiopkohgtndkop")
                    .clientKey("clientkeyHdjsbaudofuinsjdsdghhjd")
                    .server("https://jffuhvbjknfxggjfgfifgjgjxfjhygsgsyg.herokuapp.com/parse/")
    .build()
    );
    
  21. eustache509 commented on Mar 25, 2016

    @eustache509

    03-25 00:44:10.737 1300-1300/? W/PackageParser: Ignoring duplicate uses-permissions/uses-permissions-sdk-m: android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS in package: com.android.shell at: Binary XML file line #101
    03-25 00:44:10.787 1300-1300/? W/PackageParser: Ignoring duplicate uses-permissions/uses-permissions-sdk-m: android.permission.CONFIGURE_WIFI_DISPLAY in package: com.android.systemui at: Binary XML file line #119
    03-25 00:44:11.266 1300-1300/? W/PackageParser: Ignoring duplicate uses-permissions/uses-permissions-sdk-m: android.permission.WRITE_CONTACTS in package: com.android.email at: Binary XML file line #40
    03-25 00:44:11.827 1300-1300/? W/PackageParser: Ignoring duplicate uses-permissions/uses-permissions-sdk-m: android.permission.WAKE_LOCK in package: com.google.android.apps.maps at: Binary XML file line #96
    03-25 00:44:12.362 1300-1300/? W/PackageParser: No actions in intent filter at /data/app/ApiDemos/ApiDemos.apk Binary XML file line #3082
    03-25 00:44:12.362 1300-1300/? W/PackageParser: No actions in intent filter at /data/app/ApiDemos/ApiDemos.apk Binary XML file line #3088
    03-25 00:44:14.607 1300-1300/? W/System.err: at com.android.internal.alsa.AlsaCardsParser.scan(AlsaCardsParser.java:109)
    03-25 00:45:10.140 2096-2096/? I/Parse: Save Failed

  22. eustache509 commented on Mar 25, 2016

    @eustache509

    it give me different message now but , it still save fail

  23. zirinisp commented on Sep 8, 2016

    @zirinisp

    I was having the same issue and initially i though it was the cloud code that needed update. After a lot of troubleshooting I realised that the code was fine. Then I tried to see whether parse server was setup correctly. I am running it on IBM BlueMix (should be the same as heroku). The problem was the following

    var parseConfig = { databaseURI: databaseUri, appId: process.env.APP_ID, masterKey: process.env.MASTER_KEY, cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js', serverURL: ((process.env.HTTPS) ? 'https' : 'http') + host + ':' + port + mountPath, };

    The server url was resolving to "http0.0.0.0:61026/parse", which was incorrect. I updated it to include :// and the problem was resolved. The new configuration looked like the following:

    var parseConfig = { databaseURI: databaseUri, appId: process.env.APP_ID, masterKey: process.env.MASTER_KEY, cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js', serverURL: ((process.env.HTTPS) ? 'https://' : 'http://') + host + ':' + port + mountPath, };

    Such a simple mistake took me 4 hours to resolve.

  24. wellkeptbeauty commented on May 2, 2017

    @wellkeptbeauty

    var express = require('express');
    var ParseServer = require('parse-server').ParseServer;
    var path = require('path');

    var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;

    if (!databaseUri) {
    console.log('DATABASE_URI not specified, falling back to localhost.');
    }

    var api = new ParseServer({
    databaseURI: databaseUri || 'mlaburi',
    cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
    appId: process.env.APP_ID || 'APPID',
    masterKey: process.env.MASTER_KEY || 'MASTER_KEY', //Add your master key here. Keep it secret!,
    clientKey:process.env.CLIENT_KEY || 'CLIENT_KEY', //Add you client key here. Keep it secret!,
    fileKey:process.env.FILE_KEY || 'FILE_KEY', // Add you file key here,
    serverURL: process.env.SERVER_URL || 'https://myappname.herokuapp.com/parse', // Don't forget to change to https if needed
    liveQuery: {
    classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions
    }
    });

    Parse.Cloud.define("articles", function(request, response) {
    var query = new Parse.Query("Classname");
    query.equalTo("name", "rajesh");
    query.find({
    success: function(results) {
    console.log("sucess experts is",results);
    response.success(results);
    },
    error: function(error) {
    console.log("error at expert",error);
    response.error("expert failed");
    }
    });
    });
    It gives following error
    ParseError { code: undefined, message: 'unauthorized' }
    Error: {"code":141,"message":"failed"}

  25. flovilmart commented on May 6, 2017

    @flovilmart
    Contributor

    @wellkeptbeauty can you open a new issue with detailed informations? Your issue is most likely an implementation issue and not a Parse-server issue.

  26. dplewis commented on Jun 16, 2017

    @dplewis
    Member

    @flovilmart I ran into this issue today for some reason.

    I used the parse-server-example fresh out of the box added restAPIKey: 'rest' and got error unauthorized using cloud code.

    You can fix this by adding javascriptKey: 'unused' or pass in clientKey, dotNetKey, restAPIKey to be undefined.

    The issue lies with this line

    https://github.com/parse-community/parse-server/blob/master/src/middlewares.js#L19

    var info = {
        appId: req.get('X-Parse-Application-Id'),
        sessionToken: req.get('X-Parse-Session-Token'),
        masterKey: req.get('X-Parse-Master-Key'),
        installationId: req.get('X-Parse-Installation-Id'),
        clientKey: req.get('X-Parse-Client-Key'),
        javascriptKey: req.get('X-Parse-Javascript-Key'),
        dotNetKey: req.get('X-Parse-Windows-Key'),
        restAPIKey: req.get('X-Parse-REST-API-Key'),
        clientVersion: req.get('X-Parse-Client-Version')
      };
    

    req.get() is returning undefined but info has some defaults

    { appId: 'myAppId',
      sessionToken: undefined,
      masterKey: undefined,
      installationId: 'fbfa62c3-d753-2059-53b2-b6f1e2578b94',
      clientKey: undefined,
      javascriptKey: 'unused', // if your javascriptKey is 'unused' cloud code will always run
      dotNetKey: undefined,
      restAPIKey: undefined,
      clientVersion: 'js1.9.2',
      clientSDK: { sdk: 'js', version: '1.9.2' }
    
  27. BRC-solutions commented on Sep 7, 2017

    @BRC-solutions

    any solution please

  28. flovilmart commented on Sep 7, 2017

    @flovilmart
    Contributor

    Did you check @dplewis response?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type:questionSupport or code-level question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions