Reading JESSIONID cookie in Angular 6

Viewed 3058

I am working on a sample application with Spring Boot and Angular 6 I am using spring security with form based login

I am facing below issue while authentication

1)User gets authenticated using form based login and returns JSESSIONID in cookie

2)When the next request is sent by browser , the JSESSIONID cookie is NOT SENT in request causing cookie based authentication failure

After searching a bit , I have found Angular 6.x / Set jsessionid cookie answer which uses HttpInterceptor to send JSESSIONID cookie in request.

But my question is : How to read JSESSIONID cookie at first place ? Do we need to write any service for this ?

Apart from above approach , we can use {withCredentials = true} approach , but it requires to be added in every request in code which seems not an efficient solution.

Is any other approach available to solve this issue ?

Please help

1 Answers
  1. When there is successful authentication, you have to get the JSESSIONID from backend and try to store that JSESSIONID in the sesisonStorage (a STORAGE variable).
  2. Next, as you said, we need Interceptor for sure because for the next HTTP request on wards we need to set this JSESSIONID and need to trigger the rest service.
  3. So you have to write an sample interceptor service which intercepts during an HTTP call and this point get the sessionId stored in STORE and set this JSESSIONID and trigger the HTTP request. you would able to hit successfully.

I can give you sample example, we are using JWT authentication 1. during login(), am getting the Bearer toke and setting in session storage. (with encrypted format.) 2.I have written and interceptor as shown below:

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let token= JSON.parse(this.store.getStoreItem('token'));
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
    return next.handle(request);    
}
  1. The above store is the local variable for the Store service. Please take this as reference in case: https://www.js-tutorials.com/javascript-tutorial/use-localstorage-sessionstorage-using-webstorage-angular4/

Thanks and Regards, Kishore Kumar. K

Related