Leonid Bor
Leonid Bor

Reputation: 2274

No session cookie set during POST request in Angular2

I have an application, which consists of back end and front end, written with Angular 2. When first request is fired from front end, back end creates session object and sends response with Set-Cookie:JSESSIONID=29F2635FE558F131DCF937567E4C09C1;path=/;HttpOnly header (or other generated id). Browser sets cookie correctly and when I perform get requests with Http's get() method and use withCredentials: true in options object, everything works ok. But when I do the same for post request with post() method, the cookie header is not being set for some reason and I can't go past auth filter on backend.

Have anyone seen such behavior? What can be the reason of this? The request fails on OPTIONS preflight. This thing is so weird that I don't even know what additional information can be helpful, so if you have ideas -- please let me know, I'll provide any information necessary.

Examples:

This is how I get info about books (and it works ok):

this.networker.get(PATHS.base + PATHS.books, {search: this.params, withCredentials: true})
          .map((resp: Response) => {
            return resp.json() as Book[];
          });

This is how I try to add new author to catalogue

public addAuthor(author: Author): Observable<boolean> {
    const headers: Headers = new Headers();
    headers.append('Content-Type', 'application/json');
    const options: RequestOptions = new RequestOptions({withCredentials: true, headers: headers});
    return this.networker.post(PATHS.base + PATHS.authors, JSON.stringify(author), options)
      .map((resp: Response) => {
        return resp.text().localeCompare('true') === 0;
      })
  }

Networker service is just a wrapper for Angular's Http as I was trying to figure where the error happens:

@Injectable()
export class NetworkerService {

  constructor(private http: Http) {
  }

  public get(url: string, options: any): Observable<Response> {
    return this.http.get(url, options);
  }

  public post(url: string, body: any, options: any): Observable<any> {
    return this.http.post(url, body, options);
  }
}

UPD: Right now I added logic inside request filter on back end which lets OPTIONS request go past it without cookie and it does work, so the actual POST request does contain the cookie. The problem seems to be that preflight request doesn't have necessary cookie, is it how it's supposed to be?

Upvotes: 4

Views: 1031

Answers (0)

Related Questions