Angular 6.x / Set jsessionid cookie

£可爱£侵袭症+ 提交于 2019-12-13 20:26:49

问题


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


回答1:


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:

  • https://angular.io/api/common/http/HttpInterceptor
  • https://angular.io/api/http/Headers


来源:https://stackoverflow.com/questions/51601358/angular-6-x-set-jsessionid-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!