5

I am trying to login to a system. In angular 1, there was ways to set

withCredentials:true

But I could not find a working solution in angular2

export class LoginComponent {
    constructor(public _router: Router, public http: Http, ) {

    }


    onSubmit(event,username,password) {
        this.creds = {'Email': 'harikrishna@gmail.com','Password': '01010','RememberMe': true}
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');

        this.http.post('http://xyz/api/Users/Login', {}, this.creds)
              .subscribe(res => {
                  console.log(res.json().results);

              });
     }

}
Mel
  • 5,837
  • 10
  • 37
  • 42
harikrish
  • 2,009
  • 3
  • 19
  • 37

7 Answers7

8

In Angular > 2.0.0 (and actually from RC2 on), just

http.get('http://my.domain.com/request', { withCredentials: true })
maxbellec
  • 16,093
  • 10
  • 36
  • 43
  • I spent a very long time looking for this... thanks. – ARM Oct 25 '16 at 02:09
  • Likewise I spent a significant amount of time trying to work this one out. One of the issues I had was that I didn't really know what the issue was (or it took a while to track it down at least). All I saw was that I was getting a 401 response to a seemingly perfect request. – Chris Gilbert Jul 20 '17 at 13:47
5

AFAIK, right now (beta.1) the option is not available.

You have to work around it with something like this:

let _build = http._backend._browserXHR.build;

http._backend._browserXHR.build = () => {
  let _xhr =  _build();
  _xhr.withCredentials = true;
  return _xhr;
};
cexbrayat
  • 17,772
  • 4
  • 27
  • 22
  • this works in chrome and firefox but safari fails. any idea? – harikrish Feb 24 '16 at 07:14
  • Not especially for this one, but there are still some issues with Safari (like the internationalization API) with the current beta (beta.7). – cexbrayat Feb 24 '16 at 08:59
  • Can you let me know what headers you are sending wih the api's this is what i am sending headers = { headers: new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json' }) }; – harikrish Feb 24 '16 at 11:58
  • I have made a login.service.ts to log in (ionic 2), where should I put this code in order to let this work? – Brampage Apr 07 '16 at 09:41
  • This worked super well for me. Thanks! Have you built unit tests with it? I'm having trouble mocking this part out. http://stackoverflow.com/questions/37806956/unit-tests-using-withcredentials-flag – Aarmora Jun 14 '16 at 14:38
  • @cexbrayat where and how can i inject that. and how do i make any http request with above? – UzUmAkI_NaRuTo Aug 15 '16 at 05:23
2

This issue has been noted by the angular2 team.

You can find some other workarounds (one especially written as an @Injectable) following the issue link.

grebett
  • 467
  • 4
  • 10
1

If anyone is using plain JS, based on cexbrayat's answer:

app.Service = ng.core
    .Class({
        constructor: [ng.http.Http, function(Http) {
            this.http = Http;
            var _build = this.http._backend._browserXHR.build;
            this.http._backend._browserXHR.build = function() {
                var _xhr = _build();
                _xhr.withCredentials = true;
                return _xhr;
            };
        }],
Henry
  • 2,870
  • 1
  • 25
  • 17
0

I think you don't use the post metrhod the right way. You could try something like that:

onSubmit(event,username,password) {
  this.creds = {
    'Email': 'harikrishna@gmail.com',
    'Password': '01010','RememberMe': true
  }

  this.headers = new Headers();
  this.headers.append('Content-Type', 'application/json');

  this.http.post('http://xyz/api/Users/Login', 
                 JSON.stringify(this.creds),
                 { headers: headers });
}

You invert parameters. The second parameter corresponds to the content to send into the POST and should be defined as string. Objects aren't supported yet at this level. See this issue: https://github.com/angular/angular/issues/6538.

If you want to set specific headers, you need to add the Headers object within the third parameter of the post method.

Otherwise, I think the withCredentials property is related to CORS if you want to send cookies within cross domain requests. You can have a look at this link for more details:

Hope it helps you, Thierry

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0
getHeaders(): RequestOptions {
    let optionsArgs: RequestOptionsArgs = { withCredentials: true }
    let options = new RequestOptions(optionsArgs)
    return options;
  }

getAPIData(apiName): Observable<any> {`enter code here`
    console.log(Constants.API_URL + apiName);
    let headers = this.getHeaders();
    return this.http
      .get(Constants.API_URL + apiName, headers)
      .map((res: Response) => res.json())
  }

1

Enabled cors in the webapi

2

Same code works fine in the chrome(normal),Internet explorer

But it is asking windows login prompt in the incognito chrome,firefox,edge. Share the suggestions how to fix the issue

Shlok Nangia
  • 2,355
  • 3
  • 16
  • 24
0

for CORS issue with withCredentials : yes, I send the auth token as parameter

req = req.clone({
    //withCredentials: true,
    setHeaders: { token: _token },
    setParams: {
         token: _token,
     }
});
Chand Priyankara
  • 6,739
  • 2
  • 40
  • 63