【问题标题】:Angular 6.x / Set jsessionid cookieAngular 6.x / 设置 jsessionid cookie
【发布时间】:2019-01-07 03:22:14
【问题描述】:

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

【问题讨论】:

    标签: angular spring-boot oauth jsessionid angular-http-interceptors


    【解决方案1】:

    最简单的解决方案:

    constructor(public restProvider: RestProvider) { }
      intercept(request: HttpRequest<any>, next: HttpHandler):
      Observable<HttpEvent<any>> {
      if (this.restProvider.getToken() != null) {
        const clonedRequest = request.clone({
          headers: request.headers.set('X-Requested-With', 'XMLHttpRequest')
        });
      }
    }    
    

    【讨论】:

      【解决方案2】:

      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 中设置标头。

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

      【讨论】:

      • 在哪里可以导入这个?身份验证:AuthService
      • 澄清构造函数(public auth: AuthService){}。 AuthService 通常存储用户信息(名称、sessionToken、其他配置......)。我更新我的答案。检查一下!
      • 我明白你的意思,但我无法导入该类,我应该创建它还是从任何库或其他东西中导入它?我用谷歌搜索了它,但人们将那个类与 firebase 一起使用,但我对此一无所知。
      • 好的,一步一步来。您将 jsessio id 令牌存储在哪里?
      • 您能分享一下如何从令牌中获取 JSESSIONID 的代码吗?
      猜你喜欢
      • 2012-09-26
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 2016-12-10
      • 2011-02-28
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多