angular 2 http withCredentials
Asked Answered
C

4

61

I'm am trying to use withCredentials to send a cookie along to my service but can't find out how to implement it. The docs say "If the server requires user credentials, we'll enable them in the request headers" With no examples. I have tried several different ways but it still will not send my cookie. Here is my code so far.

private systemConnect(token) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-CSRF-Token', token.token);
    let options = new RequestOptions({ headers: headers });
    this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
    .subscribe(uid => {
        console.log(uid);
    });
}
Credulity answered 27/7, 2016 at 14:2 Comment(0)
H
70

Try to change your code like this

let options = new RequestOptions({ headers: headers, withCredentials: true });

and

this.http.post(this.connectUrl, <stringified_data> , options)...

as you see, the second param should be data to send (using JSON.stringify or just '') and all options in one third parameter.

Highroad answered 27/7, 2016 at 14:21 Comment(4)
It is already inside the comments for Headers and RequestOptions source files ) Until official API docs are not ready - we have to use comments in source code instead )Highroad
This is now out of date due to HttpClient being the standardIncorporeal
The right solution with HttpClient is here: #47305412Avitzur
by passing withCred server can set the cookie for cross domain, what if i am using script tag and loading the script, in that case nodejs can set the cookie? #70952415Newlin
B
33

Starting with Angular 4.3, HttpClient and Interceptors were introduced.

A quick example is shown below:

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

constructor(
      private http: HttpClient) {

this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
    .subscribe(result => {
        this.forecasts = result;
    },
    error => {
        console.error(error);
    });

Remember to provide the interceptor to your app module, as the article says:

In order to activate the interceptor for our application we need to provide it to the main application module AppModule in file app.module.ts:

Your @NgModule will need to include this in its providers:

  ...
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: WithCredentialsInterceptor,
    multi: true
  }],
  ...
Bookplate answered 10/4, 2018 at 15:48 Comment(0)
F
10

Creating an Interceptor would be good idea to inject stuff into header across the application. On the other hand, if you are looking for a quick solution that needs to be done on a per request level, try setting withCredentials to true as below

const requestOptions = {
 headers: new HttpHeaders({
  'Authorization': "my-request-token"
 }),
 withCredentials: true
};
Filip answered 25/11, 2018 at 21:19 Comment(0)
H
1

Here is a solution for Angular 17 using an interceptor:

credential.interceptor.ts

import { HttpInterceptorFn } from '@angular/common/http';

export const credentialsInterceptor: HttpInterceptorFn = (request, next) => {
  const modifiedRequest = request.clone({
    withCredentials: true
  });
  return next(modifiedRequest);
};

app.config.ts

import { ApplicationConfig } from '@angular/core';

import { provideHttpClient,
         withFetch,
         withInterceptors } from '@angular/common/http';

import { credentialsInterceptor } from './credentials.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    // ...
    provideHttpClient(withFetch(), withInterceptors([credentialsInterceptor])),
  ]
};

Side note: You can also generate interceptor using ng generate interceptor credentials.

Hemotherapy answered 30/11, 2023 at 19:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.