简体   繁体   English

如何在angular4中使用用户名和密码设置授权标头

[英]how to set authorisation header with username & password in angular4

I'm using Java Rest API services remotely. 我正在远程使用Java Rest API服务。 They are sending username & password along with services for authorization. 他们将发送用户名和密码以及授权服务。 Here i'm using angular6 and there is problem with the headers i'm passing. 在这里我正在使用angular6,而我传递的标头存在问题。 Below is my code 下面是我的代码

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders} from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { Observable, Subject } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { HttpModule } from '@angular/http';
`
@Injectable()

export class MasterService{

constructor(private http:HttpClient) { }

getApi(url): Observable<any> {
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'application/json');
headers = headers.append("Authorization", "Basic YWRtaW46YWRtaW4=");
headers = headers.append('Access-Control-Allow-Origin', '*');
headers = headers.append('UserName', 'admin');
headers = headers.append('password', 'admin');
return this.http.get(url,{ headers:headers })
  .map((res) => {
    console.log(res);
    return res;
}).catch(this.handleErrorObservable);
}
}
`

I got error like this 我有这样的错误

OPTIONS http://publicIp/coms/getEnterpriseCutomerDtls?custid=10 401 
(Unauthorized)

Access to XMLHttpRequest at 'http://publicIp/coms/getEnterpriseCutomerDtls? 
custid=10' from origin 'http://localhost:4200' has been blocked by 
CORSpolicy: Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource.

Thanks In Advance 提前致谢

I had same questions some time ago, see here: angular-2-authentication-headers 我前段时间也有相同的问题,请参见此处: angular-2-authentication-headers

On your headers authorization you must have there the user and password already encrypted like this: 在标头授权中,您必须已经在其中加密了用户名和密码,如下所示:

headers = headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));

And always make sure your CORS policy is configured correctly on your backend, I had several issues because of it... 并始终确保在后端正确配置了您的CORS策略,因此,我遇到了多个问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM