如何使用Angular 8.0.2隐藏API键
我正在尝试调用TwitchAPI。要调用此api,我们需要指定一个用户密钥。如何在代码中隐藏密钥?我不知道该怎么办如何使用Angular 8.0.2隐藏API键,angular,api,key,Angular,Api,Key,我正在尝试调用TwitchAPI。要调用此api,我们需要指定一个用户密钥。如何在代码中隐藏密钥?我不知道该怎么办 Package Version ------------------------------------------------------ @angular-devkit/architect 0.800.2 (cli-only) @angular-devkit/core 8.0.2 (cli-only) @angul
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';
}
谢谢这个问题回答了这个问题: 总结是,没有办法在客户端代码中完全隐藏API密钥。如果您直接从客户端代码发出请求,无论您做什么,任何人都可以进入浏览器开发工具并获取API密钥
当我在过去遇到一个绝对不想公开的密钥时,我通过创建一个API代理解决了这个问题。在这种情况下,API密钥安全地存在于API代码中,这是安全的,因为它是服务器端的。然后,客户端代码将调用API,而不是Twitch API。然后,API(服务器代码)将调用Twitch并将结果返回给客户端。这几乎是将密钥完全保密的唯一方法。使用代理,您也会遇到同样的问题。因为代理只是客户端和api之间的中间人,所以您现在仍然需要以某种方式对代理进行身份验证,否则人们只需查看控制台,了解如何点击代理以从您的api返回他们想要的内容;因此,在我看来,代理人或多或少只是在开玩笑
要一劳永逸地回答这个问题,您需要查看oauth2客户机授权,或者像启动服务器端渲染一样。我相信还有其他技术与这两种解决方案一样有效,但是很难找到真正安全的替代解决方案。您可以加密密钥并将其存储在本地存储器中。尽管加密并不是一种傻瓜式的机制,因为加密密钥要么驻留在客户端,要么从服务器传递。这使得它容易被修改。看看这个答案,其他任何人也可以调用
您的api
,那么这是如何解决问题的呢?您可以在代理api上为特定域添加COR,这样就可以了