在Angular 6中添加Xsrf-Token的问题

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

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

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

错误:

无法加载http://localhost/simple_api/insert.php:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*” ”。因此,'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 { }

user.services.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(()=>""));
  }

insert.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");
?>

enter image description here安慰标题的值,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'
    })
  ],
...
php angular csrf angular6 x-xsrf-token
2个回答
3
投票

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

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

另外,你为什么要混合旧的HttpModule和新的HttpClient模块? RequestOptionsHeaders在角度6中被弃用

如果使用HttpClient,默认情况下内容类型已设置为json,withCredentials设置HttpClientXsrfModule

您的请求可以简化为

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

编辑由HttpClientXsrfModule在场景后面创建的默认拦截器似乎不处理绝对URL ....

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


1
投票

服务器端,XSRF-TOKEN不是标题,而是预先设置的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;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.