Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - append withCredentials = true with every http request

I am using angular 2 (not latest as using through angular-cli: 1.0.0-beta.11-webpack.9-4) and I have to set withCredentials to true for every http request. I tried to set it up for one request using

http.get('http://my.domain.com/request', { withCredentials: true })

and everything is working fine however I am trying to use something in bootstrap as below but not getting any success

import './polyfills.ts';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/';
import {Http, Headers, BaseRequestOptions, RequestOptions, BrowserXhr} from '@angular/http';

if (environment.production) {
  enableProdMode();
}

export class MyRequestOptions extends BaseRequestOptions {
  constructor () {
    super();
    this.headers.append('withCredentials','true');
  }
}

platformBrowserDynamic().bootstrapModule(AppModule, 
  [{ provide: RequestOptions, useClass: MyRequestOptions}]
);
like image 328
Jay Avatar asked Dec 02 '25 06:12

Jay


1 Answers

I don't know if it is required anymore, but I had the same problem and I've solved in this way:

  1. Create a subclass of BaseRequestOptions (which extends RequestOptions):

    import { Headers, BaseRequestOptions } from "@angular/http";
    
    export class AuthRequestOptions extends BaseRequestOptions {
       constructor() {
          super();
          this.withCredentials = true;
       }
    }
    
  2. Register it in application bootstrap

    import { RequestOptions } from '@angular/http';
    import { AuthRequestOptions } from './<path>/AuthRequestOptions';
    
    @NgModule({
       bootstrap: [...],
       imports: [...],
       providers: [
          { provide: RequestOptions, useClass: AuthRequestOptions},
          ...
       ]
    }...
    

(In my case, this is that worked with CORS+NTLMAuthentication)

like image 159
Sierrodc Avatar answered Dec 05 '25 14:12

Sierrodc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!