3

通过 API 从表单提交中发布数据是成功的。

但是在将 X-CSRF-TOKEN 添加到标头并设置 withCredentials: true 结果数据后没有发布到名为的脚本insert.php

错误:

加载http://localhost/simple_api/insert.php失败:对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Origin”标头的值不能是通配符“ *' 当请求的凭证模式是 'include' 时。因此,不允许访问源“ http://localhost:4200 ”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

删除withCredentials: true结果数据已成功发布。但看不到 X-CSRF-TOKEN

app.module.ts

import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";
import { UsrService } from './usr.service';
import { AppComponent } from './app.component';

@NgModule({
    declarations: [
      AppComponent,
      RegisterComponent,
      LoginComponent
    ],
    imports: [
      BrowserModule,
      FormsModule,
      HttpModule,
      AppRoutingModule,
      HttpClientModule,
      HttpClientXsrfModule.withOptions({
        cookieName: 'XSRF-TOKEN',
        headerName: 'X-CSRF-TOKEN'
      })
    ],
    providers: [UsrService],
    bootstrap: [AppComponent]
  })
  export class AppModule { }

用户服务.ts

import { Http, Headers, RequestOptions, Response, URLSearchParams } from '@angular/http';
addUser(info){
    console.log(info);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, withCredentials: true });
    console.log(options);
    return this._http.post("http://localhost/simple_api/insert.php",info, options)
      .pipe(map(()=>""));
  }

插入.php

<?php
$data = json_decode(file_get_contents("php://input"));
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Headers: X-CSRF-Token, Origin, X-Requested-With, Content-Type, Accept");
?>

在此处输入图像描述 安慰标头的值,未设置 Xsrf-Token。我应该如何设置 Xsrf-Token 值?


更新:

import {HttpClient, HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

constructor(private _http:HttpClient) { }

  addUser(info){
    console.log(info);
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    // let options = new RequestOptions({ headers: headers, withCredentials: true });
    // console.log(options);
    return this._http.post("http://localhost/simple_api/insert.php",info)
        .subscribe(
                data => {
                    console.log("POST Request is successful ", data);
                },
                error => {
                    console.log("Error", error);
                }
            ); 
  }

app.module.ts

import {HttpClientModule, HttpClientXsrfModule} from "@angular/common/http";

imports: [
    ...
    HttpClientModule,
    HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-CSRF-TOKEN'
    })
  ],
...
4

2 回答 2

3

将以下标头添加到您的 php 代码中

header("Access-Control-Allow-Credentials: true");

另外,为什么要混合新旧HttpModule模块HttpClientRequestOptions并且Headers在 Angular 6 中已弃用

如果使用HttpClient,则默认情况下内容类型已设置为 json,并且withCredentialsHttpClientXsrfModule.

您的请求可以简化为

 return this._http.post("http://localhost/simple_api/insert.php",info);

编辑 在幕后创建的默认拦截器HttpClientXsrfModule似乎不处理绝对网址....

https://github.com/angular/angular/issues/18859

于 2018-09-15T06:51:23.633 回答
1

服务器端,XSRF-TOKEN不是header,而是预先设置的cookie 。这个 cookie 应该从服务器发送到您的 Angular 应用程序所在的页面,也就是说,在下面的示例中,模板“some.template.html.twig”应该加载 Angular 应用程序。

这样 Angular 将添加并发送正确的 X-XSRF 等。标题正确。

请注意:必须在 HttpOnly 选项设置为FALSE的情况下生成 cookie ,否则 Angular 将看不到它。

例如,如果您使用 Symfony,在控制器操作中您可以设置 XSRF cookie,如下所示:

namespace App\Controller;

use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
  /**
   * Disclaimer: all contents in Route(...) are example contents
   * @Route("some/route", name="my_route")
   * @param Request $request
   * @return \Symfony\Component\HttpFoundation\Response
   */
  public function someAction(Request $request, CsrfTokenManagerInterface $csrf)
  {
    $response = $this->render('some.template.html.twig');
    if(!$request->cookies->get('XSRF-TOKEN')){
      $xsrfCookie = new Cookie('XSRF-TOKEN',
        'A_Token_ID_of_your_Choice',
        time() + 3600, // expiration time 
        '/', // validity path of the cookie, relative to your server 
        null, // domain
        false, // secure: change it to true if you're on HTTPS
        false // httpOnly: Angular needs this to be false
      ); 
      $response->headers->setCookie($xsrfCookie);
    }

    return $response;
  }
}
于 2018-09-18T10:35:59.270 回答