在 Angular 中添加 Xsrf-Token 的问题 6
Issue in adding Xsrf-Token in an Angular 6
通过 API 从表单提交中发布数据成功。
但是在将 X-CSRF-TOKEN 添加到 header 并设置 withCredentials: true
之后
结果数据未发布到名为 insert.php
的脚本
错误:
Failed to load http://localhost/simple_api/insert.php: Response to
preflight request doesn't pass access control check: The value of the
'Access-Control-Allow-Origin' header in the response must not be the
wildcard '*' when the request's credentials mode is 'include'. Origin
'http://localhost:4200' is therefore not allowed access. The
credentials mode of requests initiated by the XMLHttpRequest is
controlled by the withCredentials attribute.
删除 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");
?>
安慰 header 的值,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'
})
],
...
将以下 header 添加到您的 php 代码中
header("Access-Control-Allow-Credentials: true");
此外,为什么要混合使用旧的 HttpModule
和新的 HttpClient
模块? RequestOptions
和 Headers
在 angular 6
中已弃用
如果您使用HttpClient
,内容类型默认设置为json,withCredentials
由HttpClientXsrfModule
设置。
您的请求可以简化为
return this._http.post("http://localhost/simple_api/insert.php",info);
编辑
HttpClientXsrfModule
在幕后创建的默认拦截器似乎不处理绝对 url....
Server-side,XSRF-TOKEN
不是header,而是cookie来设置预先。此 cookie 应从服务器发送到您的 Angular 应用程序所在的页面,即在下面的示例中,模板 'some.template.html.twig' 应加载 Angular 应用程序。
这样 Angular 将添加并发送正确的 X-XSRF-etc。 header 正确。
请注意:生成 cookie 时必须将 HttpOnly 选项设置为 FALSE , 否则 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;
}
}
通过 API 从表单提交中发布数据成功。
但是在将 X-CSRF-TOKEN 添加到 header 并设置 withCredentials: true
之后
结果数据未发布到名为 insert.php
错误:
Failed to load http://localhost/simple_api/insert.php: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
删除 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");
?>
更新:
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'
})
],
...
将以下 header 添加到您的 php 代码中
header("Access-Control-Allow-Credentials: true");
此外,为什么要混合使用旧的 HttpModule
和新的 HttpClient
模块? RequestOptions
和 Headers
在 angular 6
如果您使用HttpClient
,内容类型默认设置为json,withCredentials
由HttpClientXsrfModule
设置。
您的请求可以简化为
return this._http.post("http://localhost/simple_api/insert.php",info);
编辑
HttpClientXsrfModule
在幕后创建的默认拦截器似乎不处理绝对 url....
Server-side,XSRF-TOKEN
不是header,而是cookie来设置预先。此 cookie 应从服务器发送到您的 Angular 应用程序所在的页面,即在下面的示例中,模板 'some.template.html.twig' 应加载 Angular 应用程序。
这样 Angular 将添加并发送正确的 X-XSRF-etc。 header 正确。
请注意:生成 cookie 时必须将 HttpOnly 选项设置为 FALSE , 否则 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;
}
}