Search code examples
angularspring-bootoauthjsessionidangular-http-interceptors

Angular 6.x / Set jsessionid cookie


I developed my app backend using java and springboot 2.x, and in the other hand I have my angular app. I also use the OAuth2 protocol to log in, and what I need is to save the JSESSION id google provides after logging in a cookie so then send it in every request to the backend app. I read about using HttpInterceptor but I can not work it out. Any help? Thanks


Solution

  • Angular HTTPInterceptor is the most appropriate solution.

    You can use it applying the following steps:

    1: Build your HTTPInterceptor (an @Injectable service):

    @Injectable()
    export class SpringbootInterceptor implements HttpInterceptor {
      constructor(public auth: AuthService) {}
      intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
        // Clone the request to add the new header
        const clonedRequest = req.clone({ headers: req.headers.set('Set-Cookie', 'jsessionid=' + this.auth.getJSessionId()) });
    
        // Pass control to the next request
        return next.handle(clonedRequest);
      }
    }
    

    Note that .clone() method add info provided as params.

    2: Set Interceptor to your NgModule providers:

    @NgModule({
      bootstrap: [AppComponent],
      imports: [...],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: SpringbootInterceptor,
          multi: true
        }
      ]
    })
    

    Now, any request from your NgModule, set headers in SpringbootInterceptor.

    You can check more info at: