Search code examples
javascriptjavaangularcookiesjsessionid

Angular2 Set-Cookie JSESSIONID in HTTP requests


I'm using auth0/angular2-jwt library to append the JWT on each request.

I'd like to know how can I also add the JSESSIONID cookie on each request too so I hit the server side session?

Is this a good practice?

I've tried this with no success

let myHeader = new Headers();
myHeader.append('SET-COOKIE', 'JSESSIONID=<jsessionid>');

this.authHttp.get(endpoint, {headers: myHeader, withCredentials: true}).map(res => res.json()).subscribe(
  jwt => {
    ...
  },err => console.log(err));

Solution

  • Is it good practice?

    No, it is not good practice.

    From the JWT docs:

    In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie.

    Reference: https://jwt.io/introduction/https://jwt.io/introduction/

    JSESSIONID

    You need to know that there are multiple types of cookies stored in browser. Many of them can be accessible from JS code, but some of them are httpOnly. This means that browser is able to append them on every request transparently to the JS code (you will not see the cookie in your code). Default implementation of JSESSIONID on server side is the example of httpOnly cookies. There are multiple security reasons for such kind of design - JS malware on your page will not be able to steal session from the client.

    Headers

    myHeader.append('SET-COOKIE', 'JSESSIONID=<jsessionid>');

    This is not valid way to pass cookies to server. This is correct way to send response to client and set cookies on the client. If you want to pass cookies, you can use:

    myHeader.append('Cookies', 'JSESSIONID=<jsessionid>');
    

    Still, this will not work. Browser will append its own anyway. That saying, JSESSIONID should be appended automatically to your requests by the browser. If this does not work this way, the JSESSIONID cookie is not set in the browser (Check chrome developer tools, you can view cookies in application tab) or you are using remote server - on different port/server/protocol than your app (then the CORS comes in and ruins your app in this case).