【问题标题】:How to hide an API Key with Angular 8.0.2如何使用 Angular 8.0.2 隐藏 API 密钥
【发布时间】:2020-04-18 11:23:12
【问题描述】:

我正在尝试调用 twitch API。要调用这个 api,我们需要指定一个用户密钥。如何在我的代码中隐藏密钥?我不知道该怎么做。

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.800.2 (cli-only)
@angular-devkit/core         8.0.2 (cli-only)
@angular-devkit/schematics   8.0.2 (cli-only)
@schematics/angular          8.0.2 (cli-only)
@schematics/update           0.800.2 (cli-only)
rxjs                         5.5.12

在我的 app.component.ts 文件中

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaderResponse, HttpHeaders, HttpResponse, HttpErrorResponse } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'TwitchApp';
  twitch_api_key:string = 'test';
  twitch_api_Url:string = 'https://api.twitch.tv/helix/users?id=44322889';
  limit:string = '10';

  constructor(private http: HttpClient,){}

  ngOnInit(){
    this.request();
  }
  request(){
    let header = new HttpHeaders({
      'Client-ID': this.twitch_api_key
    })
    var options = {headers: header}
    this.http.get(this.twitch_api_Url,options).subscribe(
      res => {
        console.log(res)
      },
      (err: HttpErrorResponse) => {
        console.log(err.error);
        console.log(err.name);
        console.log(err.message);
        console.log(err.status);
      }
    )
  }
}

在 web 浏览器的 main.js 中

    constructor(http) {
        this.http = http;
        this.title = 'TwitchApp';
        this.twitch_api_key = 'test';
        this.twitch_api_Url = 'https://api.twitch.tv/helix/users?id=44322889';
        this.limit = '10';
    }

谢谢

【问题讨论】:

  • 您可以加密密钥并将其存储在本地存储中。尽管加密不是万无一失的机制,因为加密的密钥要么驻留在客户端,要么从服务器传递。这使得它容易被修改。看看这个答案stackoverflow.com/questions/59509684/…

标签: angular api key


【解决方案1】:

使用代理,您会遇到同样的问题。因为代理只是作为客户端和您的 api 之间的中间人,因此您现在仍然必须以某种方式对代理进行身份验证,否则人们可以查看控制台并了解如何点击代理以从您的 api 返回他们想要的内容;因此,在我看来,代理或多或少只是把罐子踢下去。

要一劳永逸地回答这个问题,您要么需要查看 oauth2 客户端授权,要么需要启动服务器端渲染所有内容。我确信还有其他技术与这两种解决方案一样有效,但是很难找到真正安全的替代解决方案。

【讨论】:

    【解决方案2】:

    这个问题得到了回答:How to secure the JavaScript API Access Token?

    总结是没有办法在您的客户端代码中完全隐藏 API 密钥。如果您直接从客户端代码发出请求,那么无论您做什么,任何人都可以进入浏览器开发工具并获取您的 API 密钥。

    当我过去使用绝对不想公开的密钥遇到此问题时,我通过创建 API 进行代理解决了它。在这种情况下,API 密钥安全地保存在 API 代码中,因为它是服务器端的,所以它是安全的。然后,您的客户端代码将调用您的 API,而不是 Twitch API。然后,您的 API(服务器代码)将调用 Twitch 并将结果返回给您的客户端。这几乎是完全保密该密钥的唯一方法。

    【讨论】:

    • 其他人也可以打电话给your api,那怎么解决这个问题呢?
    • 您可以在代理 api 上为特定域添加 cors,它会起作用
    • 然而 CORS 仅在网络浏览器中有效
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 2016-07-23
    • 1970-01-01
    • 2021-01-27
    • 2020-04-15
    • 2020-09-28
    相关资源
    最近更新 更多