2

I'm trying to send credentials via http request using Angular 2, but Angular 2 Http get request does not send credentials. What am I doing wrong?

var creds = "username=" + this.username + "&password=" + this.password;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

http.get('http://localhost:3000', {
    headers: headers,
    credentials: creds
})
.map(res => res.json())
.subscribe(
    data => this.data(data),
    err => this.error(err),
    () => console.log('Done')
);
jo_va
  • 13,504
  • 3
  • 23
  • 47
Ignat
  • 3,727
  • 6
  • 16
  • 17
  • `RequestOptionsArgs` doesn't have credentials attribute: https://angular.io/docs/ts/latest/api/http/RequestOptionsArgs-interface.html, it's a `Header` : https://angular.io/docs/ts/latest/api/http/Headers-class.html, you can set the headers based on this spec: https://fetch.spec.whatwg.org/#headers-class, that credentials attribute sets a different thing, I believe you are looking for the `Authorization` Header instead. – Langley Jan 14 '16 at 16:43

3 Answers3

2

I think you want to use the HTTP basic authentication to access a secured HTTP resource. So your credentials need to be set within the Authorization header, as described below:

createAuthorizationHeader(headers:Headers) {
  headers.append('Authorization', 'Basic ' +
    btoa('username:password')); 
}

getData() {
  var headers = new Headers();
  this.createAuthorizationHeader(headers);

  this.http.get('http://localhost:3000'', {
    headers: headers
  }).map(res => res.json())
    .subscribe(
      data => this.data(data),
      err => this.error(err),
      () => console.log('Done')
}

You can notice that your credentials must be base64-encoded.

Your request seems to be a cross domain one so CORS concepts apply. You can have a look at this link for more details: http://restlet.com/blog/2015/12/15/understanding-and-using-cors/. That said I don't think that your problem is related to CORS.

I can't see any credentials attribute in the RequestOptions class.

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1

Try this code, it must work:

var creds = "username=" + this.username + "&password=" + this.password;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');

http.get('http://localhost:3000' + creds, {
 headers: headers,
 })
 .map(res => res.json())
 .subscribe(
 data => this.data(data),
 err => this.error(err),
 () => console.log('Done')
Maksim
  • 2,396
  • 6
  • 18
  • 27
0

within your app config try:

  $httpProvider.defaults.withCredentials = true;

So your app config will look something like this:

angular.module('myappService', [
    'fdvService.constants',
]).config(['$httpProvider',function ($httpProvider) {
      $httpProvider.defaults.withCredentials = true;
  }]);
Amonn
  • 84
  • 6