angular - 如何使用 Angular 8.0.2 隐藏 API key

标签 angular api key

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

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

谢谢

最佳答案

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

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

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

关于angular - 如何使用 Angular 8.0.2 隐藏 API key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59518546/

相关文章:

angular - 使用angular提交后如何获取所选 ionic 单选按钮的值

Angular2 相对路线在守卫中导航

api - Instagram API 响应代码 400(错误请求)

android - Kotlin改型预期为begin_array,但在第1行为begin_object

php - 为什么不删帖子呢?

Angular 4 - Nginx/刷新显示错误页面

api - 如何将数据从 Controller 传递到 go lang 中的表单?

c++ - 如何实现具有 2 个键的哈希表?

git push origin master 给出错误权限被拒绝(github)

javascript - Angular 2 通过 [class.className] 绑定(bind)添加多个类