首页 > 解决方案 > Angular 6.x / 设置 jsessionid cookie

问题描述

我使用 java 和 springboot 2.x 开发了我的应用程序后端,另一方面,我有我的 Angular 应用程序。我还使用 OAuth2 协议登录,我需要的是在登录 cookie 后保存谷歌提供的 JSESSION id,然后在每个请求中将其发送到后端应用程序。我阅读了有关使用 HttpInterceptor 的信息,但我无法解决。有什么帮助吗?谢谢

标签: angularspring-bootoauthjsessionidangular-http-interceptors

解决方案


Angular HTTPInterceptor 是最合适的解决方案

您可以通过以下步骤使用它:

1:构建您的 HTTPInterceptor(@Injectable 服务):

@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);
  }
}

请注意,.clone()方法添加作为参数提供的信息。

2:将拦截器设置为您的 NgModule 提供者

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

现在,来自 NgModule 的任何请求,在SpringbootInterceptor中设置标头。

您可以在以下位置查看更多信息:


推荐阅读