[C0006] Unauthorized and [C0005] Request contains unknown parameter: network

thanks hifilorau, what do you mean by move api? is this on the frontend? I understand that Moralis.Auth.requestMessage is in the backend, in authService.ts but my code is the same with the help you give me, I just change the network name to networkType is what I notice differently, and in the same way it gives me mistake. And should I download the version of moralis sdk? I currently have:

this in the backend:

 "@moralisweb3/common-core": "2.22.0",
     "@moralisweb3/common-sol-utils": "^2.22.0",
     "@moralisweb3/evm-utils": "2.22.0",
     "@moralisweb3/parse-server": "2.22.0",
     "moralis": "2.22.0",

and on the front end:

     "moralis": "2.22.0",
     "moralis-v1": "1.13.0",
     "react-moralis": "^1.4.2",

If you can give me more details I would be grateful.

I think the problem is the backend, because when I follow the frontend with console.log()
never goes from here:

  const { message } = await Moralis.Cloud.run("requestMessage", {
         address: account,
         chain: parseInt(chainID.testNet),
         networkType: "evm",
       });

it goes to catch and the error it throws is

error Error: [C0006] Request failed, Bad Request(400): Unauthorized
     at handleError (RESTController.js:438:17)
     at async Login(UserState.tsx:206:27);

and putting more console.log() in:

export async function requestMessage({ address, chain, network }: { address: string; chain: string; network: "evm" }) {

   const url = new URL(config.SERVER_URL);
   const now = new Date();
   const expirationTime = new Date(now.getTime() + EXPIRATION_TIME);
   console.log('url.hostname', url.hostname)
   console.log('url', url.toString())
   const result = await Moralis.Auth.requestMessage({
     address,
     chain,
     networkType: network,
     domain: url.hostname,
     statement: STATEMENT,
     uri: url.toString(),
     expirationTime: expirationTime.toISOString(),
     timeout: TIMEOUT,
   });

   const { message, id, profileId } = result.toJSON();
   authRequests.set(message, { id, profileId });
   console.log('result', result)

   return message;
}

This console returns an empty array
console.log('result', result)

Yeah my moralis.auth.request message is on the backend. But i was having issues when trying to use the nextJS 13 new app router. When i moved my backend API route from app/api/auth/request-message to pages/api/auth/request-message i was able to get things to work.

Hmm… i am not using the Moralis.cloud functions but based on your error my guess is that you need to pass in your Moralis API Key at some point for you Moralis cloud function to work.

I understand, yes, it’s just that I don’t see an example for the cloud in moralis documentation, so I asked what is the best way to do the authentication, it should be manual with ethers as I see in the documentation. But if I don’t want to do the authentication with next, what would be the way.
Regarding this, I am new to backend and I am still learning, sorry for the lack of knowledge. If it’s not a bother, could you give me an example of how I move this to this path to test this solution. I don’t see any other solution.

for example this is a manual way to do the authentication. https://docs.moralis.io/authentication-api/evm/integrations/parse-server-nodejs, but in the last part of the documentation, there are 2 functions. one that is called connectToMetamask, and another that is called handleAuth, in this last function handleAuth I do not understand or do not see where it comes from

const { message } = await requestMessage(account, chain);
const { user } = await verifyMessage(message, signature);

I see that these functions are in the backend. not in the frontend should I pass these functions to the frontend? Is this the way you did the authentication?.
From what I understand, then I should make 2 requests with the cloud for these two functions?
I wanted to try this way, authentication but I am not clear about the functions.

So I think that for those functions the cloud should look something like this:

Parse.Cloud.define('requestMessage', async ({ params }: any) => {
   const { address, chain, network } = params;
   const message = await requestMessage({
     address,
     chain,
     network,
   });

   return { message };
});

Parse.Cloud.define('requestVerifyMessage', async ({ params }: any) => {
   const { message, signature } = params;
   const user = await verifyMessage({
     message,
     signature
   });

   return { user };
});

I have tried everything, but apparently it is moralis. since I changed the authentication code to:

authService.ts:

const Login = async() => {
     setStateCircularProgress(true);
     const provider = "metamask";

  
     await enableWeb3({ provider: provider });
    
     try {
       // Connect to Metamask

       const { signer, chain, account } = await connectToMetamask();

       if (!state.authenticated) {
         if (chain != chainID.testNet) {
           await switchNetworkPolygon();
         }


       }
       if (!account) {
         throw new Error(
           "Connecting to chain failed, as no connected account was found"
         );
       }
       if (!chain) {
         throw new Error(
           "Connecting to chain failed, as no connected chain was found"
         );
       }
       const { message } = await Moralis.Cloud.run("requestMessage", {
         address: account,
         chain: parseInt(chainID.testNet),
       });

       const signature = await signer.signMessage(message);

      
       const { user } = await Moralis.Cloud.run("requestVerifyMessage", {
         message,
         signature,
       });

       console.log("message", message);
       console.log("account", account);
       console.log("user", user);

       setValuesAlertFunc(true, "Login success", "success");
       setStateCircularProgress(false);
     } catch(e) {
       const errorMessage = JSON.stringify(e);
       const errorObject = JSON.parse(errorMessage);
       setValuesAlertFunc(true, errorObject.message, "error");
       console.log("error", e);
     }
     setStateCircularProgress(false);
   };

y me sigue dando error de mensaje:

error Error: [C0006] Request failed, Bad Request(400): Unauthorized
    at handleError (RESTController.js:438:17)
    at async Login (UserState.tsx?t=1685654058847:219:11)

y los datos se estan pasando. no se que mas hacer o probar. please ayuda :(.

/* eslint-disable no-console */

/* eslint-disable @typescript-eslint/no-unused-vars */

/* eslint-disable @typescript-eslint/no-explicit-any */

import Moralis from 'moralis';

import { authRequests } from '../store';

import { ParseServerRequest } from '../utils/ParseServerRequest';

import config from '../config';

const STATEMENT = 'Welcome to Koolinart';

const EXPIRATION_TIME = 900000;

const TIMEOUT = 15;

export async function requestMessage({ address, chain, network }: { address: string; chain: string; network: 'evm' }) {

  const url = new URL(config.SERVER_URL);

  const now = new Date();

  const expirationTime = new Date(now.getTime() + EXPIRATION_TIME);

  const result = await Moralis.Auth.requestMessage({

    address,

    chain,  

    domain: url.hostname,

    statement: STATEMENT,

    uri: url.toString(),

    expirationTime: expirationTime.toISOString(),

    timeout: TIMEOUT,

  });

  console.log('url.hostname', url.hostname)

  console.log('url', url.toString())

  const { message, id, profileId } = result.toJSON();

  authRequests.set(message, { id, profileId });

  console.log('url', url.toString())

  return message;

}

export async function verifyMessage({ network, signature, message }: any) {

  const storedData = authRequests.get(message);

  if (!storedData) {

    throw new Error('Invalid message');

  }

  const { id: storedId, profileId: storedProfileId } = storedData;

  const authData = {

    id: storedProfileId,

    authId: storedId,

    message,

    signature,

    network,

  };

  // Authenticate

  const user = await ParseServerRequest.post({

    endpoint: `/users`,

    params: {

      authData: {

        moralis: authData,

      },

    },

    useMasterKey: true,

  });

  // Update user moralisProfile column

  await ParseServerRequest.put({

    endpoint: `/users/${user.objectId}`,

    params: {

      moralisProfileId: storedProfileId,

    },

    useMasterKey: true,

  });

  // Get authenticated user

  const updatedUser = await ParseServerRequest.get({

    endpoint: `/users/${user.objectId}`,

    useMasterKey: true,

  });

  return updatedUser;

}

I will leave 2 more imports that have authService.ts, which is authRequests,
ParseServerRequest.

ParseServerRequest.ts:

/* eslint-disable @typescript-eslint/no-explicit-any */

/* eslint-disable @typescript-eslint/no-unused-vars */

import { CoreProvider, RequestController } from '@moralisweb3/common-core';

import config from '../config';

export class ParseServerRequest {

  static get(arg0: { endpoint: string; useMasterKey: boolean; }) {

    throw new Error('Method not implemented.');

  }

  static put(arg0: { endpoint: string; params: { moralisProfileId: string; }; useMasterKey: boolean; }) {

    throw new Error('Method not implemented.');

  }

  protected readonly requestController: RequestController;

  static post: any;

  constructor() {

    const core = CoreProvider.getDefault();

    this.requestController = RequestController.create(core);

  }

  getHeaders = (useMasterKey: boolean) => ({

    ...(useMasterKey && { 'X-Parse-Master-Key': config.MASTER_KEY }),

    'X-Parse-Application-Id': config.APPLICATION_ID,

  });

  post = <Result>({

    endpoint,

    params,

    useMasterKey,

  }: {

    endpoint: string;

    params: Record<string, unknown>;

    useMasterKey: boolean;

  }) =>

    this.requestController.post(`${config.SERVER_URL}/${endpoint}`, undefined, params, {

      headers: this.getHeaders(useMasterKey),

    }) as Promise<Result>;

  put = <Result>({

    endpoint,

    params,

    useMasterKey,

  }: {

    endpoint: string;

    params: Record<string, unknown>;

    useMasterKey: boolean;

  }) =>

    this.requestController.put(`${config.SERVER_URL}/${endpoint}`, undefined, params, {

      headers: this.getHeaders(useMasterKey),

    }) as Promise<Result>;

  get = <Result>({ endpoint, useMasterKey }: { endpoint: string; useMasterKey: boolean }) =>

    this.requestController.get(`${config.SERVER_URL}/${endpoint}`, undefined, {

      headers: this.getHeaders(useMasterKey),

    }) as Promise<Result>;

}

store.ts- authRequests:

// TODO: replace for proper data store, and remove expired authRequests

export const authRequests = new Map<string, { id: string; profileId: string }>();

I don’t understand if I modified something and it’s wrong. please help.

Hi @davidzuccarini

When I tested auth logic on the latest parse server code it seems to work without any errors.

We need to track what is causing the error from your code. So can you try adding some console.logs for debugging?
You can add the console logs to log the params at the frontend requestMessage code and also to log the params received at the backend and passed to the Moralis.Auth.requestMessage function.

hi john, yes, the data from the params is arriving, the cloud networkType is not, but that value is written inside the cloud, the wallet and the address are arriving. I leave the log and the cloud

cloud:

Parse.Cloud.define('requestMessage', async ({ params }: any) => {

  const { address, chain, networkType } = params;

  console.log('address', address)

  console.log('chain', chain)

  console.log('network', networkType)

  const message = await requestMessage({

    address,

    chain,

    networkType: "evm",

  });

  return { message };

});

log:

address 0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe
chain 80001
network undefined
error: Failed running cloud function requestMessage for user undefined with:
  Input: {"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001}
  Error: {"message":"[C0006] Request failed, Bad Request(400): Unauthorized","code":141} {"error":{"code":141,"message":"[C0006] Request failed, Bad Request(400): Unauthorized"},"functionName":"requestMessage","params":{"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001}}
error: [C0006] Request failed, Bad Request(400): Unauthorized {"code":141,"stack":"Moralis SDK Core Error: [C0006] Request failed, Bad Request(400): Unauthorized\n    at RequestController.makeError (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:1224:20)\n    at RequestController.<anonymous> (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:1205:38)\n    at step (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:83:23)\n    at Object.throw (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:64:53)\n    at rejected (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:55:65)\n    at runMicrotasks (<anonymous>)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"}

the undefined network, in the same way it does not matter since that value is written within the cloud.

That is in the code that the log leaves above. You can notice that they reach the cloud. It is giving me an error in this moralis function. returns the array empty. I mention it above with hifilorau, when debugging the internal code of the requestMessage function that is in the auth directory and calls the requestMessage function, inside it this other function is executed:

const result = await Moralis.Auth.requestMessage({
     address,
     chain,
     networkType,
     domain: url.hostname,
     uri: url.toString(),
     statement: STATEMENT,
     notBefore: now.toISOString(),
     expirationTime: expirationTime.toISOString(),
     timeout: TIMEOUT,
   });

the result of this: await Moralis.Auth.requestMessage. is an empty array too.

I clarify that the values url.hostname, url.toString(), STATEMENT, now.toISOString(), expirationTime.toISOString(), TIMEOUT. They are in the code you can also see them in the code above, if I debug their values are there.

requestMessage:

address 0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe
chain 80001
network undefined
address 0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe
chain
url.hostname localhost
url.toString() http://localhost:1337/server
STATEMENT Welcome to Koolinart
now.toISOString() 2023-06-03T06:41:57.687Z
expirationTime.toISOString() 2023-06-03T06:56:57.687Z
TIMEOUT 15
error: Failed running cloud function requestMessage for user undefined with:
  Input: {"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001}
  Error: {"message":"[C0006] Request failed, Bad Request(400): Unauthorized","code":141} {"error":{"code":141,"message":"[C0006] Request failed, Bad Request(400): Unauthorized"},"functionName":"requestMessage","params":{"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001}}
error: [C0006] Request failed, Bad Request(400): Unauthorized {"code":141,"stack":"Moralis SDK Core Error: [C0006] Request failed, Bad Request(400): Unauthorized\n    at RequestController.makeError (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:1224:20)\n    at RequestController.<anonymous> (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:1205:38)\n    at step (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:83:23)\n    at Object.throw (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:64:53)\n    at rejected (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:55:65)\n    at processTicksAndRejections (node:internal/process/task_queues:96:5)"}

I leave the complete log with the logs inside requestMessage.

once I opened a thread with the same error, they corrected my code, and it was good to try so many things, well, I had things wrong in the code, the truth is that I modified it to try to fix it because it worked, in the end I couldn’t do it It will work, I went to bed the next day, update moralis, and pop only the error was corrected so I fixed it. and again I return the error. After updating I have not tried to downgrade since I do not want anything else to break. I’m struggling to put the project into production. things change. I say all this to tell the experience. something if you notice metamask was updated and this happened.

Hi @davidzuccarini

I was only able to reproduce a similar error when I manually use the wrong API key :sweat_smile:. So can you once verify if you have entered the correct API key in your .env file?

Please if that is the case.

If I put api 1 and api 2, it does not give me an error for the login with mail, but it does give me an error with metamask. In the backend, if I place any of these api (api1 and api2) to start the backend, the stream gives me an error.
in example:

Moralis.start({
   apiKey: config.MORALIS_API_KEY,
});

this is the backend. here is api 3. and it doesn’t give me an error.

but the front and backend do have different apikey. if I have to initialize web3 differently as it should be. It is not clear to me the use of the api then. here is the error.

If I put api 3 in the front, it starts me in. but it gives me apikey error. If I put api 1 or 2 in the front, it starts the session but metamask gives me an error. And if I change the way to start with Moralis.start the backend doesn’t serve the streams.

I must start 2 one with

 Moralis.start({
   apiKey: config.MORALIS_API_KEY_STREAM,
});

and another with

Moralis.start({
   apiKey: config.MORALIS_API_KEY_WEB3,
});

?
In summary, frontend web3api, backend streams api, is this wrong? It must be initialized in another way, because the apikeys are different.
I hope you understand me.

Hey @davidzuccarini can you show me the error that you get from using API 1, 2, 3?

Just wondering what error message that you get, but that’s definitely strange :thinking:

Let me explain: the streams API is the one in the backend executing Moralis.start. In the frontend if I try api 1 and 2 there is no news, I log in normally but via email (with the login system implemented via parse server email) but it does not log in with metamask, it gives me the error C0006 not authorized. so they are 2 different api both in frontend and backend. one is from streams (backend) and one is from web3 (frontend). Should the 2 api’s be the same? both the backend and the frontend? And if I use streams and web3, should I use 2 Moralis.start? (in the backend)? one for web3 and one for streams? because it does not log in with metamask, use api 1 or api 2 with metamask the error is:

, the metamask version I use is 10.30.4. but johnversus tells me that it gives me this error if I use the wrong api key but I try api 1 and api 2 and it’s the same. and the full code of what i use is the one i left above. I have node version v16.18.1

please any can help me. johnversus, YosephKS, cryptokid

the error has nothing to do with it because I use moralis-v1 to execute the

const { message } = await Moralis.Cloud.run("requestMessage", {
         // domain: serverUrl,
         address: account,
         chain: parseInt(chainID.testNet),
         networkType: "evm",
       });

and the await Moralis.authenticate() I use from moralis-v1?

Hi @davidzuccarini

You can only use one API key to start the sdk. So use Moralis.start only once with one API key.

Did you rebuild and restart the server after updating the API key in env? If not the updated env variable will not be used in the code.

The Unauthorized error that you are getting is only related to the incorrect API key. You can also test it by calling any API endpoint and you should get the same Unauthorized error.

Please clarify something for me, it doesn’t matter that the backend api is stream, and the frontend api is web3? yes, in the backend I run yarn build, and yarn dev, delete node_modules. yarn.lock. install the dependencies again, and run the above commands.

Same API key can be used for both API’s so it does not matter.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.