postgresql 无法将SSL安全数据库连接到typeorm

kuuvgm7e  于 2023-04-20  发布在  PostgreSQL
关注(0)|答案(7)|浏览(188)

这是我第一次使用NestJS,我在连接Digitalocean上托管的Postgres数据库到NestJS时遇到了麻烦。
我在网上搜索解决方案并尝试添加"ssl": "true" or "extra": { "ssl": "true" }
这里是我的ormconfig.json

{
  "type": "postgres",
  "host": "host",
  "port": "port",
  "username": "username",
  "password": "password",
  "database": "database",
  "extra": {
    "ssl": "true"
  },
  "synchronize": "true",
  "logging": "true",
  "entities": ["src/**/*.entity.ts", "dist/**/*.entity.js"]
}

我希望它连接到服务器。我得到的错误是[TypeOrmModule] Unable to connect to the database. error: no pg_hba.conf entry for host "", user "", database "", SSL off

k3bvogb1

k3bvogb11#

如果有人有同样的问题,我通过添加一个ssl字段并设置我从Digital Ocean获得的ca证书来修复它。这是我的ormconfig看起来像:

module.exports = {
  name: 'default',
  type: 'postgres',
  host: 'host',
  port: port,
  username: 'username',
  password: 'password',
  database: 'database',
  synchronize: true,
  dropSchema: false,
  logging: true,
  ssl: {
    ca: process.env.SSL_CERT,
  },
  entities: ['src/**/*.entity.ts', 'dist/**/*.entity.js'],
};
2w2cym1i

2w2cym1i2#

如果你使用typeorm从localhost连接到heroku上的postgres数据库,这是可行的。
ormconfig.json

{
  "name": "default",
  "type": "postgres",
  "url": "postgres://username:password@host:port/database",
  "synchronize": true,
  "logging": true,
  "entities": ["src/entity/*.*"],
  "ssl": true,
  "extra": {
    "ssl": {
      "rejectUnauthorized": false
    }
  }
}
ubof19bj

ubof19bj3#

这是我在Heroku上的NestJS TypeORM配置:

TypeOrmModule.forRoot({
  type: 'postgres',
  url: process.env.DATABASE_URL,
  autoLoadEntities: true,
  ssl:
    process.env.NODE_ENV === 'production'
      ? { rejectUnauthorized: false }
      : false,
}),

SSL选项是必需的,如下所述:https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js

wztqucjr

wztqucjr4#

ssl: {
    rejectUnauthorized: false,
    ca: fs.readFileSync('/path/to/server-certificates/root.crt').toString(),
    key: fs.readFileSync('/path/to/client-key/postgresql.key').toString(),
    cert: fs.readFileSync('/path/to/client-certificates/postgresql.crt').toString(),
  },

通过https://node-postgres.com/features/ssl

qoefvg9y

qoefvg9y5#

将这一行添加到配置设置中:

options: { encrypt: false }

您的配置应类似于以下内容:

TypeOrmModule.forRoot({
  type: 'mssql',
  host: 'your_db_server_address',
  port: 1433,
  username: 'user',
  password: 'pwd',
  database: 'your_db_name_here',
  entities: [Subscription],
  options: { encrypt: false }
  
})
0ejtzxu1

0ejtzxu16#

您可以将PQSSLMODE环境变量设置为require-libpq将自动读取这些数据,如果没有其他设置,并建立安全连接。
标签:https://www.postgresql.org/docs/current/libpq-envars.html

rm5edbpk

rm5edbpk7#

与上面类似,我花了很长时间摆弄ssl和no-authorize和ca证书,但只是传递env var:PGSSLMODE=no-verify为我修复了所有问题。

相关问题