Angular 5 无法从 HttpXsrfTokenExtractor 获取 XSRF 令牌

问题描述 投票:0回答:2

我正在尝试通过 绝对 URL 向 Spring(基本身份验证)安全的 Rest API 发出 POST 请求。
读到 Angular 省略了自动将 X-XSRF-TOKEN 插入绝对 URL 的请求标头后,我尝试实现一个 HttpInterceptor 来添加令牌。

在我原来的 /signin POST 请求中,我创建了必要的 authorization: Basic 标头,以确保 Spring 对请求进行身份验证。
返回的响应标头包含预期的 set-cookie 令牌:

Set-Cookie:XSRF-TOKEN=4e4a087b-4184-43de-81b0-e37ef953d755; Path=/


但是,在我的自定义拦截器类中,当我尝试从注入的 HttpXsrfTokenExtractor 获取下一个请求的令牌时,它返回 null

这是我的拦截器类的代码:

import {Injectable, Inject} from '@angular/core';
import { Observable } from 'rxjs/Rx';
import {HttpInterceptor, HttpXsrfTokenExtractor, HttpRequest, HttpHandler, 
HttpEvent} from '@angular/common/http';


@Injectable()
export class HttpXsrfInterceptor implements HttpInterceptor {

   constructor(private tokenExtractor: HttpXsrfTokenExtractor) {}

   intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     let requestMethod: string = req.method;
     requestMethod = requestMethod.toLowerCase();

     if (requestMethod && (requestMethod === 'post' || requestMethod === 'delete' || requestMethod === 'put' )) {
         const headerName = 'X-XSRF-TOKEN';
         let token = this.tokenExtractor.getToken() as string;
         if (token !== null && !req.headers.has(headerName)) {
           req = req.clone({ headers: req.headers.set(headerName, token) });
         }
      }

    return next.handle(req);
   }
}


上面代码中的tokenExtractor.getToken()返回null。我期望它从我之前的 /signin 请求的 Spring (Set-Cookie) 响应标头返回令牌。

我阅读了有关创建拦截器的相关文章:
angular4 httpclient csrf does not send x-xsrf-token

但是除此之外我找不到太多有关 HttpXsrfTokenExtractor 的文档:
https://angular.io/api/common/http/HttpXsrfTokenExtractor

问题:为什么 HttpXsrfTokenExtractor.getToken() 返回 null?

此外,我将拦截器类作为提供者添加到app.module
这是我的 app.module.ts:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { LocationStrategy, HashLocationStrategy, APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HttpClientXsrfModule } from '@angular/common/http';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AlertModule } from 'ng2-bootstrap';
import { routing, appRouterProviders } from './app.routing';
import { HttpXsrfInterceptor } from './httpxrsf.interceptor';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './registration/register.component';
import { HomeComponent } from './home/home.component';

@NgModule({
    declarations: [AppComponent,
               LoginComponent,
               RegisterComponent,
               HomeComponent],
    imports: [BrowserModule,
          FormsModule,
          ReactiveFormsModule,
          HttpClientModule,
          HttpClientXsrfModule, // Adds xsrf support
          AlertModule.forRoot(),
          routing],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
    providers: [
        appRouterProviders,
        [{provide: APP_BASE_HREF, useValue: '/'}],
        [{provide: LocationStrategy, useClass: HashLocationStrategy}],
        [{provide: HTTP_INTERCEPTORS, useClass: HttpXsrfInterceptor, multi: true }]
    ],
    bootstrap: [AppComponent]
})
export class AppModule {}


另一件需要注意的事情是,我在 Node.js 上从 localhost:3000 运行我的 Angular 前端,从 localhost:8080 运行 Spring Rest 后端。 它们位于不同的端口,因此使用 absolute urls 发出 http 请求的原因。当来自不同域上的请求响应时,浏览器会阻止 Set-Cookie 工作吗?

我还能错过什么吗?

谢谢您的帮助。

-------------------------------------------------------------
[2018 年 1 月 7 日更新]

修复

我使用 Webpack 开发服务器 来提供 Angular 代码。我通过为指向我的后端 Rest API 的 url 配置一个 proxy 解决了这个问题。

这意味着从浏览器发出的所有请求现在都只能发送到端口 3000 的开发服务器,即使对于 Rest API 调用也是如此。
webpack 开发服务器 看到任何具有配置模式的请求 url(例如 /api/...)时,它会替换为对 http://localhost:8080 上后端服务器的调用(在我的案件)。

这是我添加到 webpack.dev.js 文件的 devServer 部分的内容:

proxy: {
    '/api': {
    'target': 'http://localhost:8080',
    'pathRewrite': {'^/api' : ''}
    //Omits /api from the actual request. E.g. http://localhost:8080/api/adduser -> http://localhost:8080/adduser
    }
}



通过此设置,我不再从 Angular 代码发出跨域(跨源)请求或不再使用绝对 URL。这极大地简化了事情,因为我不再与 Angular XSRF (CSRF) 机制作斗争。它只是默认工作。我也不需要使用 HttpInterceptor 手动插入 X-XSRF-TOKEN

设置开发服务器代理的额外好处是客户端请求不再是绝对的,因此我不需要更改生产中的所有 Rest API 调用。

我希望这对遇到同样问题/理解的人有用。

Webpack 开发服务器代理文档参考:
https://webpack.js.org/configuration/dev-server/#devserver-proxy

spring-security csrf webpack-dev-server angular5 x-xsrf-token
2个回答
4
投票

由于您使用不同的端口(3000 和 8080),您正在发出跨源请求,因此您将无法读取从服务器发送的客户端中的 cookie。如果您想以这种方式分离客户端和服务器,则需要使用代理,以便客户端和服务器应用程序通过相同的协议 (http/https)、域和端口提供服务。如果您使用 Spring Boot,我建议您查看 Spring Cloud Netflix,特别是 Zuul (https://cloud.spring.io/spring-cloud-netflix/single/spring-cloud-netflix.html#_router_and_filter_zuul)。


0
投票

使用 withCredentials: true 属性,以便它(XSRF-TOKEN)可以通过角度代码读取,如下所示 -

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  withCredentials: true //this is required so that Angular returns the Cookies received from the server. The server sends cookies in Set-Cookie header. Without this, Angular will ignore the Set-Cookie header
}; 
© www.soinside.com 2019 - 2024. All rights reserved.