Angular 9 中的 Env 实现

Env Implementation of in Angular 9

有没有办法在 Angular 中隐藏 API 凭据?

我尝试在我的项目中实现代码,但似乎无法正常工作, 不知道这个是否兼容angular9,我按照步骤操作,还是报错

请参阅下面的 link 和我的示例代码, https://www.ninadsubba.in/blog/setup-dotenv-to-access-environment-variables-in-angular-9

environment.ts

.env

Terminal Output

我已经安装了以下软件包: npm install --save-dev yargs dotenv and npm install @types/node --save-dev 还是出现这个错误,求教帮助我解决了这个问题,以清楚地了解 dotenv 如何有助于隐藏 angular 中的凭据,或者如果这仅适用于 node.js,对不起,我是 angular 中的新手。提前致谢。

您可以使用 webpack 中的设置混淆代码以使其更难阅读(我相信这是默认完成的)。

The article you mentioned 非常具有误导性和危险性,暗示您可以在用户自己的计算机上“隐藏”用户的凭据。引用文章:

"Googling for help on setting up environment variables for Angular is a nightmare;"

这是有充分理由的!!

anything you give to the client, can be read by them. You cannot hide it.

这意味着如果您需要 api 密钥来访问您的 api,那么他们 看到它。

请记住,如果您需要与您的 api 通信,您将发送一个带有授权 headers 的 http 请求,这些 总是 出现在每个使用您的 Angular 应用程序的人的网络选项卡中的纯文本。

一个潜在的解决方案 是更改您的身份验证方式。不使用密钥,而是根据 api 对用户进行身份验证(一种备受推崇的做法是使用 OAuth) 这是一个很好的 package for angular oauth. This allows users to send a username/password combo (or use a third party provider) to exchange this for a token that they can then send back and forth with your server to authenticate their api requests. Your server should always verify the integrity of this token when receiving a request. Firebase 也是处理身份验证的常用资源,因此您不必这样做。