{"id":"78f1d195b52a8640","repo":"mongodb/node-mongodb-native","slug":"host-host-is-not-valid-for-oidc-authenticatio","errorCode":null,"errorMessage":"Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(',')}'","messagePattern":"Host '(.+?)' is not valid for OIDC authentication with ALLOWED_HOSTS of '(.+?)'","errorType":"exception","errorClass":"MongoInvalidArgumentError","httpStatus":null,"severity":"error","filePath":"src/mongo_client.ts","lineNumber":662,"sourceCode":"    }\n    if (typeof options.srvHost === 'string') {\n      const hosts = await resolveSRVRecord(options);\n\n      for (const [index, host] of hosts.entries()) {\n        options.hosts[index] = host;\n      }\n    }\n\n    // It is important to perform validation of hosts AFTER SRV resolution, to check the real hostname,\n    // but BEFORE we even attempt connecting with a potentially not allowed hostname\n    if (options.credentials?.mechanism === AuthMechanism.MONGODB_OIDC) {\n      const allowedHosts =\n        options.credentials?.mechanismProperties?.ALLOWED_HOSTS || DEFAULT_ALLOWED_HOSTS;\n      const isServiceAuth = !!options.credentials?.mechanismProperties?.ENVIRONMENT;\n      if (!isServiceAuth) {\n        for (const host of options.hosts) {\n          if (!hostMatchesWildcards(host.toHostPort().host, allowedHosts)) {\n            throw new MongoInvalidArgumentError(\n              `Host '${host}' is not valid for OIDC authentication with ALLOWED_HOSTS of '${allowedHosts.join(\n                ','\n              )}'`\n            );\n          }\n        }\n      }\n    }\n\n    this.topology = new Topology(this, options.hosts, options);\n    // Events can be emitted before initialization is complete so we have to\n    // save the reference to the topology on the client ASAP if the event handlers need to access it\n\n    this.topology.once(Topology.OPEN, () => this.emit('open', this));\n\n    for (const event of MONGO_CLIENT_EVENTS) {\n      this.topology.on(event, (...args: any[]) => this.emit(event, ...(args as any)));\n    }","sourceCodeStart":644,"sourceCodeEnd":680,"githubUrl":"https://github.com/mongodb/node-mongodb-native/blob/3366c21a6311e02f1be91da982f9b93d3cce99a0/src/mongo_client.ts#L644-L680","documentation":"Thrown during MongoClient connect when MONGODB-OIDC authentication is configured and a target host is not in the ALLOWED_HOSTS list (defaults to localhost and MongoDB Atlas/Cloud hosts). This guard prevents OIDC token theft by ensuring tokens are only sent to approved hosts. The error lists the offending host and the current ALLOWED_HOSTS for diagnosis. Skipped when a service ENVIRONMENT is configured (machine-to-machine).","triggerScenarios":"Connecting to a host not matching any wildcard in ALLOWED_HOSTS while using authMechanism=MONGODB-OIDC and no ENVIRONMENT. Connecting through a proxy or custom domain, or pointing at an on-prem host not added to ALLOWED_HOSTS.","commonSituations":"Self-hosted MongoDB with OIDC where the hostname was not allowlisted; typos in the connection string host; SRV records resolving to unexpected hosts; forgetting to set ALLOWED_HOSTS for non-Atlas deployments.","solutions":["Add the host to ALLOWED_HOSTS via authMechanismProperties in the connection string: ?authMechanismProperties=ALLOWED_HOSTS:myhost.example.com,*.mydomain.com","Verify the connection string host matches an entry (supports * wildcards) in ALLOWED_HOSTS.","For non-interactive service auth, set ENVIRONMENT (e.g. aws, gcp, azure) which bypasses the host check."],"exampleFix":"// before\nconst uri = 'mongodb://user@db.internal.corp:27017/?authMechanism=MONGODB-OIDC';\n\n// after\nconst uri =\n  'mongodb://user@db.internal.corp:27017/?authMechanism=MONGODB-OIDC' +\n  '&authMechanismProperties=ALLOWED_HOSTS:db.internal.corp,*.internal.corp';","handlingStrategy":"validation","validationCode":"function validateOidcHosts(hosts, allowedHosts) {\n  const ok = hosts.every(h =>\n    allowedHosts.some(pattern => hostMatchesWildcards(h, [pattern]))\n  );\n  if (!ok) throw new Error('Host not in ALLOWED_HOSTS');\n}","typeGuard":null,"tryCatchPattern":"try { await client.connect(); } catch (e) {\n  if (e instanceof MongoInvalidArgumentError && /ALLOWED_HOSTS/.test(e.message)) {\n    // fix connection string and retry\n  }\n  throw e;\n}","preventionTips":["Pre-register every target host in ALLOWED_HOSTS","Use ENVIRONMENT for non-interactive service auth to bypass host checks","Validate hosts before connect in integration tests"],"tags":["oidc","auth","allowed-hosts","security"],"analyzedSha":"3366c21a6311e02f1be91da982f9b93d3cce99a0","analyzedAt":"2026-08-04T13:40:15.335Z","schemaVersion":2}