如何在api中使用api传递用户名和密码? [英] how to pass username and password with api in angular?

查看:512
本文介绍了如何在api中使用api传递用户名和密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API.如果打开,则应输入用户名和密码.如何获取该API中的数据?如果我写get("....api-url...."),它会显示unauthorized error.如何将用户名和密码传递给该API?

I have an API. If you open that you should enter username and password. How can I get the data which is in that API? If I write get("....api-url...."), it shows unauthorized error. How can I pass a username and password to that API?

constructor(private _http: Http) {
    this.getMyBlog();
}

private getMyBlog() {
    return this._http.get('http://localhost:8088/.../...')
        .map((res: Response) => res.json())
        .subscribe(data => {
            this.data = data;
            console.log(this.data);
        });
}

推荐答案

我假设您想将它与GET请求一起作为查询参数发送?

I'm assuming you want to send it along with the GET request as query parameters?

这是一个糟糕的错误做法(用户密码是URL的一部分-虽然正文内容可能受SSL保护,但攻击者完全可以看到实际的URL)-阅读更多@

This is terrible bad practice (the users password is part of the URL - while the body contents may be protected by SSL, the actual URL will be fully visible to attackers) - read more @ https://www.fullcontact.com/blog/never-put-secrets-urls-query-parameters/

此外,不建议使用HTTP模块-请改用HttpClientModule( https://angular.io/guide/http )

Also, the HTTP Module is being deprecated - look at using the HttpClientModule instead (https://angular.io/guide/http)

如果您仍然想这样做:

public getMyBlog(username, password): Observable<any> {
  const params = new HttpParams().set('username', username).set('password', password);
  return this.http.get('...apiurl...', { params });
}

发帖:

public getMyBlog(username, password): Observable<any> {
  const body = { username, password };
  return this.http.post('...apiurl...', body);
}

获取请求的更好方法是在标头中发送令牌:

A better way for get requests is to send a token in the headers:

public getMyBlog(token) {
  const headers = new HttpHeaders().set('Authorization', token);
  return this.http.get('...apiurl...', { headers });
}

这篇关于如何在api中使用api传递用户名和密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆