我是Angular 2开发的新手。在我的应用程序中,我有登录模块,其中将用户名和密码[纯文本]传递给Web APi控制器,以便从角度服务类进行身份验证。
下面是我的角度2服务方法,它调用web api。
authenticate(model) {
let headers = new Headers({ 'Content-Type': 'application/json; charste=utf-8' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(model);
return this.http.post('http://localhost:24314/api/Users/', body, options)
.map(response => response.json()).catch(this.handleErrorObservable);
}
不知何故,我想在发送到web api时加密此密码字段。
任何帮助或建议都将不胜感激。
提前致谢。
答案 0 :(得分:2)
要将凭据传递到服务器,请通过HTTPS发送;无需自己加密。将所有内容发送到HTTPS;今天,HTTP不再是一个可靠的选择。
凭据不应出现在您的代码中,而是由用户以表格形式输入。你把它们放在内存中并发送到服务器。理想情况是服务器将它们作为身份验证令牌进行交换,因此您可以在客户端(例如,在localstorage中)存储此令牌。然后,您可以通过将令牌发送到每个请求来对服务器进行身份验证(当然,始终使用HTTPS)。
答案 1 :(得分:0)
加密密码的最佳和简单的方法是javascript btoa方法,你可以像这样使用
authenticate(model) {
let data = btoa(model.user_name + ':' + model.password);
let headers = new Headers({ 'Content-Type': 'application/json; charste=utf-8' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(data);
return this.http.post('http://localhost:24314/api/Users/', body, options)
.map(response => response.json()).catch(this.handleErrorObservable);
}
通过使用您不必使用任何第三方库进行加密或类似的东西 有关更多信息,请参阅此处
答案 2 :(得分:-1)
authenticate(model) {
let headers = new Headers({ 'Content-Type': 'application/json; charste=utf-8' });
let options = new RequestOptions({ headers: headers });
model.pass = yourEncryptionFunction(model.pass, 'superStringPass');
let body = JSON.stringify(model);
return this.http.post('http://localhost:24314/api/Users/', body, options)
.map(response => response.json()).catch(this.handleErrorObservable);
}
yourEncryptionFunction(password: string, cryptoKey: string): string {
// .. do something here.. use a lib or just add a static value..
return ....;
}
问题是,每个人都可以看到你的加密方法及其使用的加密密钥等等。所以这样做并没有什么好处。 :)
有趣的图书馆: