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

Hello, the authentication was working. and now it gives me an error, update moralis, and it stopped working. It was working normally with metamask, the authentication left the front and server code.

error:

error: Failed running cloud function requestMessage for user undefined with:
  Input: {"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001,"network":"evm"}
  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,"network":"evm"}}
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)"}

function login:

const Login = async () => {

    setStateCircularProgress(true);

    try {

      const provider = "metamask";

      await enableWeb3({ provider: provider });

      const { account, chainId } = Moralis;

      const { message } = await Moralis.Cloud.run("requestMessage", {

        address: account,

        chain: parseInt(chainID.testNet),

        network: "evm",

      });

      console.log("account", account);

      console.log("chainId", chainId);

      if (!account) {

        throw new Error(

          "Connecting to chain failed, as no connected account was found"

        );

      }

      if (!chainId) {

        throw new Error(

          "Connecting to chain failed, as no connected chain was found"

        );

      }

      if (!state.authenticated) {

        if (chainId != chainID.testNet) {

          await switchNetworkPolygon();

        }

        await Moralis.authenticate({

          signingMessage: message,

        }).then(async (user: any) => {

          const userMarketType = user!.get("loginType");

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

          console.log("user", user);

          const ethAddres = user!.get("ethAddress");

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          await fetchTokenBalance(ethAddres);

        });

      }

      setValuesAlertFunc(true, "Login success", "success");

      setStateCircularProgress(false);

    } catch (e) {

      const errorMessage = JSON.stringify(e);

      const errorObjeto = JSON.parse(errorMessage);

      setValuesAlertFunc(true, errorObjeto.message, "error");

      console.log("error", e);

      setStateCircularProgress(false);

    }

  };

The auth code is the same as Moralis in the repo at https://github.com/MoralisWeb3/Moralis-JS-SDK/tree/main/demos/parse-server-migration

Hey @davidzuccarini,

what do you mean by updating Moralis? do you mean updating to the newest SDK version?

yes yosep, hi, I update the sdk and moralis dependencies, I’m looking at the examples in the documentation and I don’t see anything similar in the documentation to the login function, could you tell me what’s wrong? since I have tried several things and if it does not give me error c0005 it gives me error c0006 and this worked, hahaha and I keep what works, it is not touched.

You can take a look at the code that I left, the back end code is the same as the repository, so I didn’t leave an example of it.

The other error I get is this:

error: Failed running cloud function requestMessage for user undefined with:
   Input: {"domain":"http://localhost:1337/server","address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001,"network":"evm"}
   Error: {"message":"[C0005] Request contains unknown parameter: network. This operation supports the following parameters: domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout","code":141} {"error":{"code":141,"message":"[C0005] Request contains unknown parameter: network. This operation supports the following parameters: domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout"},"functionName":"requestMessage","params":{"address":"0x0bf75e9e3251fda1a66bd449c8630f16a2c3cabe","chain":80001,"domain":"http://localhost:1337/server","network" :"evm"}}
error: [C0005] Request contains unknown parameter: network. This operation supports the following parameters: domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout {"code":141,"stack":"Moralis SDK Error: [C0005] Request contains unknown parameter: network. This operation supports the following parameters: domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout\n at OperationRequestValidator.

note: I noticed that the repo code that I left was updated, so I proceeded to update the code thinking that when updating the dependencies, this would be the problem and now I get the error that I left. (I mean the backend, I updated it to see if it was a solution).

current code frontend function login:

const Login = async () => {

    setStateCircularProgress(true);

    try {

      const provider = "metamask";

      await enableWeb3({ provider: provider });

      const { account, chainId,  } = Moralis;

      const { message } = await Moralis.Cloud.run("requestMessage", {

        domain: serverUrl,

        address: account,

        chain: parseInt(chainID.testNet),

        network: "evm",

      });

      console.log("account", account);

      console.log("chainId", chainId);

      if (!account) {

        throw new Error(

          "Connecting to chain failed, as no connected account was found"

        );

      }

      if (!chainId) {

        throw new Error(

          "Connecting to chain failed, as no connected chain was found"

        );

      }

      if (!state.authenticated) {

        if (chainId != chainID.testNet) {

          await switchNetworkPolygon();

        }

        await Moralis.authenticate({

          signingMessage: message,

        }).then(async (user: any) => {

          const userMarketType = user!.get("loginType");

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

          console.log("user", user);

          const ethAddres = user!.get("ethAddress");

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          await fetchTokenBalance(ethAddres);

        });

      }

      setValuesAlertFunc(true, "Login success", "success");

      setStateCircularProgress(false);

    } catch (e) {

      const errorMessage = JSON.stringify(e);

      const errorObjeto = JSON.parse(errorMessage);

      setValuesAlertFunc(true, errorObjeto.message, "error");

      console.log("error", e);

      setStateCircularProgress(false);

    }

  };

I also clarify that it receives 3 parameters address, chain, network, what is in the code the extra domain option is for test, I don’t know if you have to add data to start the session with metamask.

I also think that the error is due to the metamask being updated. should it have something to do with it?

also check this documentation https://docs.moralis.io/authentication-api/evm/integrations/parse-server-nodejs, there is an example of the back end repository code in that documentation and at the end of the documentation there is a Example that seems to be for the frontend but the implementation is not clear to me, such as where the requestMessage(account, chain) and verifyMessage(message, signature) function comes from; are calls to the cloud for the backend? Here I should call the cloud, I don’t see more similarities in the documentation to the parse server? thank you for always helping me.

Hi @davidzuccarini

Can you try updating the network param name to networkType. It looks like network parma is renamed as per the latest sdk.

Yes, it was like that from the beginning when it worked, and it gives the same error [C0005] Request contains unknown parameter: network. This operation supports the following parameters: domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout

I am not sure why it throws error now. Possible due to some update in self host code.

Since the error says these are the only supported params, we can completely remove the network or networkType param.
domain, chainId, address, statement, uri, expirationTime, notBefore, resources, timeout

ChainId should be enough to identify the network.

Exactly it should work hahaha, typical errors in development. Well, I attached the current code of backend parse-server.

main server:

/* eslint-disable consistent-return */

/* eslint-disable @typescript-eslint/no-empty-function */

/* eslint-disable no-undef */

/* eslint-disable no-unused-expressions */

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

/* eslint-disable @typescript-eslint/no-var-requires */

/* eslint-disable no-console */

/* eslint-disable prefer-const */

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

import cors from 'cors';

import express from 'express';

import Moralis from 'moralis';

import config from './config';

import { parseServer } from './parseServer';

// @ts-ignore

import { streamsSync } from '@moralisweb3/parse-server';

import http from 'http';

// @ts-ignore

import ParseServer from 'parse-server';

import { parseDashboard } from "./parseDashboard";

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

// @ts-ignore

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

// @ts-ignore

const Web3 = require('web3');

export const app = express();

import { authRouter } from './auth/authRouter';

import { errorHandler } from './middlewares/errorHandler';

const port = config.HTTP_PORT;

Moralis.start({

  apiKey: config.MORALIS_API_KEY,

});

const verifySignature = (req: any, secret: string) => {

  const providedSignature = req.headers["x-signature"]

  if(!providedSignature) {throw new Error("Signature not provided")}

  const generatedSignature= Web3.utils.sha3(JSON.stringify(req.body)+secret)

  if(generatedSignature !== providedSignature) {throw new Error("Invalid Signature")}

}

app.use(express.urlencoded({ extended: true }));

app.use(express.json());

app.use(cors());

app.use(

  streamsSync(parseServer, {

    apiKey: config.MORALIS_API_KEY,

    webhookUrl: config.STREAMS_WEBHOOK_URL

    }

  ),

);

app.use(`/server`, parseServer.app);

app.use(`/dashboard`, parseDashboard);

app.use('/auth', authRouter);

app.use(errorHandler);

app.use(express.static('public'));

app.post(`/streams`, async (req: any, res: any) => {

  try{

    verifySignature(req, config.MORALIS_API_KEY)

    const { data, _tagName, eventName }: any = parseEventData(req);

    console.log(data);

    await parseUpdate(`SFS_${eventName}`, data);

    return res.status(200).json();

  }catch(error){

    console.log('errorStream', error)

  }

  res.send('ok');

})

const httpServer = http.createServer(app);

httpServer.listen(port, async () => {

  if (config.USE_STREAMS) {

    // eslint-disable-next-line no-console

    console.log(

      `Moralis Server is running on port ${port} and stream webhook url ${config.STREAMS_WEBHOOK_URL}`,

    );

  } else {

    // eslint-disable-next-line no-console

    console.log(`Moralis Server is running on port ${port}.`);

  }

});

// This will enable the Live Query real-time server

ParseServer.createLiveQueryServer(httpServer);

main.ts from the /cloud folder:

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

/* eslint-disable etc/no-commented-out-code */

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

/* eslint-disable @typescript-eslint/no-var-requires */

declare const Parse: any;

import "./collections"

import "./functionMarket"

import "./renderNft"

import "./stripe"

import "./user"

import "./sendingEmails"

import { requestMessage } from '../auth/authService';

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

  const { address, chain, network } = params;

  const message = await requestMessage({

    address,

    chain,

    network,

  });

  return { message };

});

Parse.Cloud.define('getPluginSpecs', () => {

  // Not implemented, only excists to remove client-side errors when using the moralis-v1 package

  return [];

});

Parse.Cloud.define('getServerTime', () => {

  // Not implemented, only excists to remove client-side errors when using the moralis-v1 package

  return null;

});

export default Parse

MoralisEthAdapter.ts:

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

// Note: do not import Parse dependency. see https://github.com/parse-community/parse-server/issues/6467

/* global Parse */

import Moralis from 'moralis';

// eslint-disable-next-line @typescript-eslint/no-explicit-any

function validateAuthData(authData: any) {

  const { signature, data, message, network, id, authId } = authData;

  return Moralis.Auth.verify({

    message,

    signature,

    network,

  })

    .then((result) => {

      const authenticated = result.toJSON();

      if (id === data.profileId && authId === data.id) {

        authData.chainId = result.result.chain.decimal;

        authData.nonce = authenticated.nonce;

        authData.address = result.result.address.checksum;

        authData.version = authenticated.version;

        authData.domain = authenticated.domain;

        authData.expirationTime = authenticated.expirationTime;

        authData.notBefore = authenticated.notBefore;

        authData.resources = authenticated.resources;

        authData.statement = authenticated.statement;

        authData.uri = authenticated.uri;

        authData.moralisProfileId = authenticated.profileId;

      }

      throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Moralis auth failed, invalid data');

    })

    .catch(() => {

      // @ts-ignore (see note at top of file)

      throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Moralis auth failed, invalid data');

    });

}

function validateAppId() {

  return Promise.resolve();

}

export default {

  validateAuthData,

  validateAppId,

};

authService.ts:

/* 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,

    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 });

  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;

}
1 Like

You closed the thread and it’s not resolved. :frowning: leave the server code to see what is wrong

The error is not solved after updating the params? Do you see any other errors?

Ahh…I see in authService.ts: it expects the network param here. So maybe try removing the network here and build the server code again.

ok, but where exactly? if you mean this:

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

I get the same error

You are getting this same error?
Does the error still say unknown parameter: network even after removing the network?

not the other error I mention:

 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,"networkType": "evm"}}
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\\Programming\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:1224 :20)\n at RequestController.<anonymous> (C:\\Users\\david\\Documents\\Programming\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\common-core\\lib \\cjs\\index.cjs:1205:38)\n at step (C:\\Users\\david\\Documents\\Programming\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\ common-core\\lib\\cjs\\index.cjs:83:23)\n at Object.throw (C:\\Users\\david\\Documents\\Programming\\react\\Koolinart\\backend\ \node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:64:53)\n at rejected (C:\\Users\\david\\Documents\\Programming\\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)"}
info: Create new client: 6896f143-9e37-4409-b421-260621bcd0d7

metamask opens , it says metamask connect, but I can’t sign the message, and the error appears

Hi @davidzuccarini

If your metamask opened for message signature then the error could be in your frontend code.

Can you show your frontend code where you are using the authenticate function?

The function called to authenticate is this:

import { Moralis } from "moralis-v1";

const Login = async () => {

    setStateCircularProgress(true);

    try {

      const provider = "metamask";

      await enableWeb3({ provider: provider });

      const { account, chainId,  } = Moralis;

      const { message } = await Moralis.Cloud.run("requestMessage", {

        // domain: serverUrl,

        address: account,

        chain: parseInt(chainID.testNet),

        networkType: "evm",

      });

      console.log("account", account);

      console.log("chainId", chainId);

      if (!account) {

        throw new Error(

          "Connecting to chain failed, as no connected account was found"

        );

      }

      if (!chainId) {

        throw new Error(

          "Connecting to chain failed, as no connected chain was found"

        );

      }

      if (!state.authenticated) {

        if (chainId != chainID.testNet) {

          await switchNetworkPolygon();

        }

        await Moralis.authenticate({

          signingMessage: message,

        }).then(async (user: any) => {

          const userMarketType = user!.get("loginType");

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

          console.log("user", user);

          const ethAddres = user!.get("ethAddress");

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          await fetchTokenBalance(ethAddres);

        });

      }

      setValuesAlertFunc(true, "Login success", "success");

      setStateCircularProgress(false);

    } catch (e) {

      const errorMessage = JSON.stringify(e);

      const errorObjeto = JSON.parse(errorMessage);

      setValuesAlertFunc(true, errorObjeto.message, "error");

      console.log("error", e);

    }

    setStateCircularProgress(false);

  };

and metamask never asks me to sign the message, just connect.

Looks like your metamask only opened for connection, not for signing the signature message.
Allow me to check for more details in your code

Ok thanks Johnversus, if you don’t sign, before I get a warning message that you trust the page where you are signing now, no. and the truth is that the login functions have not been touched, because everything was already fine.

Can you share a snap of that warning message?

I can’t capture it because it no longer logs me in, this was when it worked normally before the signature came out, and before signing, a warning message came out, sorry for my bad English, if sometimes I don’t make myself understood by English

1 Like

I was getting this same message re: network but only in production and eventually i found a message buried in my logs that my mongoDB wasn’t connecting. My requestMesssage funciton just looks like this:

const message = await Moralis.Auth.requestMessage({
            address,
            chain,
            networkType: 'evm',
            domain: process.env.APP_DOMAIN,
            statement: 'Please sign this message to confirm your identity.',
            uri: process.env.NEXTAUTH_URL,
            timeout: 60,
   address,
            chain,
            networkType: 'evm',
            domain: process.env.APP_DOMAIN,
            statement: 'Please sign this message to confirm your identity.',
            uri: process.env.NEXTAUTH_URL,
            timeout: 60,
    })

with Moralis 2.21 and next auth 4.22. I also ended up moving all of my auth work into the pages/api instead of the app/api routes