首页 文章

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

提问于
浏览
2

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

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

Error:

无法加载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'
    })
  ],
...

2 回答

  • 3

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

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

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

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

    您的请求可以简化为

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

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

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

  • 1

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

    这样Angular将添加并发送正确的X-XSRF等 . 头正确 .

    Please note :必须在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;
      }
    }
    

相关问题