How to call REST service with Basic Authentication in Angularjs 2.0?

时光总嘲笑我的痴心妄想 提交于 2019-12-23 10:08:25

问题


I have java REST services and consumer in Angularjs 1.3. Services are JSON based and expect BASIC authentication (username-password). In AgJs 1.3, I used Base64 factory code (found on google) for creating basic authentication token from username and password and able to consume services SUCCESSFULLY.

I read HTTP class in AgJs 2.0 documentation but I didn't find any information about basic authentication.

Could anybody please provide sample code to consume REST services in Angularjs 2.0 using BASIC authentication?

Thanks in advance!

Best Regards!

My AgJs 1.3 code:

var url = "http://x.x.x.x:xxxx/data/" + number;

$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode('username' + ':' + 'password');
$http.defaults.headers.common['Content-Type'] = 'application/json';

$http({ method: 'GET', url: url }).
        success(function (data, status, headers, config) {
           alert(data);
        }).
        error(function (data, status, headers, config) {
            alert("error: " + data);
        });

回答1:


I have just make a post from angular2 to a server that has Basic auth and this works:

    sendAuthentification(credentials: string): Observable<any> {
          var headers = new Headers();
          headers.append('Authorization', 'Basic ' +  btoa('user:pass'));

          return this.http.get("http://ip/yourpost", headers});
   }

Hope this answer your question.




回答2:


Depends if you're using the new Angular2 http api, or something external like fetch.

If the latter you could do something like this, just remember to wrap with zone:

myHeaders = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + Base64.encode('username' + ':' + 'password')
    }
return Zone.bindPromiseFn(fetch)(
            url,
            {
                method: 'GET',
                headers: myHeaders,
                body: JSON.stringify(myData)
            }).then(
                r => {return r.json()}
        );


来源:https://stackoverflow.com/questions/31671132/how-to-call-rest-service-with-basic-authentication-in-angularjs-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!