質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

CSRF

クロスサイトリクエストフォージェリ (Cross site request forgeries、CSRF)は、 外部Webページから、HTTPリクエストによって、 Webサイトの機能の一部が実行されてしまうWWWにおける攻撃手法です。

XAMPP

XAMPP(ザンプ)は、ウェブアプリケーションの実行に必要なフリーソフトウェアをパッケージングしたApacheディストリビューションです。 XAMPPひとつインストールするだけで、Apache、MySQL、PHP、Perlなどのソフトウェアと、 phpMyAdminなどの管理ツール、SQLiteなどのソフトウェアやライブラリモジュールなどを利用することが可能です。

Q&A

解決済

2回答

2796閲覧

cakePHP3.7 CSRF token mismatchエラーについて

nori-p

総合スコア13

CakePHP

CakePHPは、PHPで書かれたWebアプリケーション開発用のフレームワークです。 Ruby on Railsの考え方を多く取り入れており、Railsの高速性とPHPの機動性を兼ね備えています。 MVCやORMなどを「規約優先の考え方」で利用するため、コードを書く手間を省くことができます。 外部のライブラリに依存しないので、単体での利用が可能です。

CSRF

クロスサイトリクエストフォージェリ (Cross site request forgeries、CSRF)は、 外部Webページから、HTTPリクエストによって、 Webサイトの機能の一部が実行されてしまうWWWにおける攻撃手法です。

XAMPP

XAMPP(ザンプ)は、ウェブアプリケーションの実行に必要なフリーソフトウェアをパッケージングしたApacheディストリビューションです。 XAMPPひとつインストールするだけで、Apache、MySQL、PHP、Perlなどのソフトウェアと、 phpMyAdminなどの管理ツール、SQLiteなどのソフトウェアやライブラリモジュールなどを利用することが可能です。

0グッド

0クリップ

投稿2018/12/21 06:16

編集2018/12/21 14:56

実現したいこと

xampp,CakePHPで試しにフォームを作成しております。
下記エラーを解消したいです。
よろしくお願い致します。

発生している問題・エラーメッセージ

submitしたところ、以下のエラーメッセージが出力されました。

CSRF token mismatch. Cake\Http\Exception\InvalidCsrfTokenException

ソースコード

templateはWEBのサンプルをそのまま貼り付けました。

HTML

1<h1>Sample Page</h1> 2<p> 3 <?php 4 5 //フォームの作成 6 echo $this->Form->create(); 7 //コントロールを配置 8 echo $this->Form->control('名前'); 9 echo $this->Form->control('住所'); 10 echo $this->Form->control('メール'); 11 echo $this->Form->control('備考'); 12 13 echo $this->Form->button('送信'); 14 15 //フォームの終了 16 echo $this->Form->end(); 17 18 ?> 19</p> 20</div>

src/Application.php

PHP

1<?php 2/** 3 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) 4 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) 5 * 6 * Licensed under The MIT License 7 * For full copyright and license information, please see the LICENSE.txt 8 * Redistributions of files must retain the above copyright notice. 9 * 10 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) 11 * @link https://cakephp.org CakePHP(tm) Project 12 * @since 3.3.0 13 * @license https://opensource.org/licenses/mit-license.php MIT License 14 */ 15namespace App; 16 17use Cake\Core\Configure; 18use Cake\Core\Exception\MissingPluginException; 19use Cake\Error\Middleware\ErrorHandlerMiddleware; 20use Cake\Http\BaseApplication; 21use Cake\Http\Middleware\CsrfProtectionMiddleware; 22use Cake\Routing\Middleware\AssetMiddleware; 23use Cake\Routing\Middleware\RoutingMiddleware; 24 25/** 26 * Application setup class. 27 * 28 * This defines the bootstrapping logic and middleware layers you 29 * want to use in your application. 30 */ 31class Application extends BaseApplication 32{ 33 /** 34 * {@inheritDoc} 35 */ 36 public function bootstrap() 37 { 38 // Call parent to load bootstrap from files. 39 parent::bootstrap(); 40 41 if (PHP_SAPI === 'cli') { 42 try { 43 $this->addPlugin('Bake'); 44 } catch (MissingPluginException $e) { 45 // Do not halt if the plugin is missing 46 } 47 48 $this->addPlugin('Migrations'); 49 } 50 51 /* 52 * Only try to load DebugKit in development mode 53 * Debug Kit should not be installed on a production system 54 */ 55 if (Configure::read('debug')) { 56 $this->addPlugin(\DebugKit\Plugin::class); 57 } 58 } 59 60 /** 61 * Setup the middleware queue your application will use. 62 * 63 * @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to setup. 64 * @return \Cake\Http\MiddlewareQueue The updated middleware queue. 65 */ 66 public function middleware($middlewareQueue) 67 { 68 $middlewareQueue 69 // Catch any exceptions in the lower layers, 70 // and make an error page/response 71 ->add(ErrorHandlerMiddleware::class) 72 73 // Handle plugin/theme assets like CakePHP normally does. 74 ->add(new AssetMiddleware([ 75 'cacheTime' => Configure::read('Asset.cacheTime') 76 ])) 77 78 // Add routing middleware. 79 // Routes collection cache enabled by default, to disable route caching 80 // pass null as cacheConfig, example: `new RoutingMiddleware($this)` 81 // you might want to disable this cache in case your routing is extremely simple 82 ->add(new RoutingMiddleware($this, '_cake_routes_')) 83 84 // Add csrf middleware. 85 ->add(new CsrfProtectionMiddleware([ 86 'httpOnly' => true 87 ])); 88 return $middlewareQueue; 89 } 90} 91

config/routes.php

PHP

1<?php 2/** 3 * Routes configuration 4 * 5 * In this file, you set up routes to your controllers and their actions. 6 * Routes are very important mechanism that allows you to freely connect 7 * different URLs to chosen controllers and their actions (functions). 8 * 9 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) 10 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) 11 * 12 * Licensed under The MIT License 13 * For full copyright and license information, please see the LICENSE.txt 14 * Redistributions of files must retain the above copyright notice. 15 * 16 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) 17 * @link https://cakephp.org CakePHP(tm) Project 18 * @license https://opensource.org/licenses/mit-license.php MIT License 19 */ 20use Cake\Http\Middleware\CsrfProtectionMiddleware; 21use Cake\Routing\RouteBuilder; 22use Cake\Routing\Router; 23use Cake\Routing\Route\DashedRoute; 24 25/** 26 * The default class to use for all routes 27 * 28 * The following route classes are supplied with CakePHP and are appropriate 29 * to set as the default: 30 * 31 * - Route 32 * - InflectedRoute 33 * - DashedRoute 34 * 35 * If no call is made to `Router::defaultRouteClass()`, the class used is 36 * `Route` (`Cake\Routing\Route\Route`) 37 * 38 * Note that `Route` does not do any inflections on URLs which will result in 39 * inconsistently cased URLs when used with `:plugin`, `:controller` and 40 * `:action` markers. 41 * 42 * Cache: Routes are cached to improve performance, check the RoutingMiddleware 43 * constructor in your `src/Application.php` file to change this behavior. 44 * 45 */ 46Router::defaultRouteClass(DashedRoute::class); 47 48Router::scope('/', function (RouteBuilder $routes) { 49 // Register scoped middleware for in scopes. 50 $routes->registerMiddleware('csrf', new CsrfProtectionMiddleware([ 51 'httpOnly' => true 52 ])); 53 54 /** 55 * Apply a middleware to the current route scope. 56 * Requires middleware to be registered via `Application::routes()` with `registerMiddleware()` 57 */ 58 $routes->applyMiddleware('csrf'); 59 60 /** 61 * Here, we are connecting '/' (base path) to a controller called 'Pages', 62 * its action called 'display', and we pass a param to select the view file 63 * to use (in this case, src/Template/Pages/home.ctp)... 64 */ 65 $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']); 66 67 /** 68 * ...and connect the rest of 'Pages' controller's URLs. 69 */ 70 $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']); 71 72 /** 73 * Connect catchall routes for all controllers. 74 * 75 * Using the argument `DashedRoute`, the `fallbacks` method is a shortcut for 76 * 77 * ``` 78 * $routes->connect('/:controller', ['action' => 'index'], ['routeClass' => 'DashedRoute']); 79 * $routes->connect('/:controller/:action/*', [], ['routeClass' => 'DashedRoute']); 80 * ``` 81 * 82 * Any route class can be used with this method, such as: 83 * - DashedRoute 84 * - InflectedRoute 85 * - Route 86 * - Or your own route class 87 * 88 * You can remove these routes once you've connected the 89 * routes you want in your application. 90 */ 91 $routes->fallbacks(DashedRoute::class); 92}); 93 94/** 95 * If you need a different set of middleware or none at all, 96 * open new scope and define routes there. 97 * 98 * ``` 99 * Router::scope('/api', function (RouteBuilder $routes) { 100 * // No $routes->applyMiddleware() here. 101 * // Connect API actions here. 102 * }); 103 * ``` 104 */ 105

補足

画面のソースにはhiddenのtokenが出力され、
Chromeのデベロッパーツールで確認する限り、
SESSIONにもtokenと同じ値が設定されていました。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2018/12/21 06:46

src/Application.php と config/route.php 両方提示すべし
nori-p

2018/12/21 14:28

特に変更していませんが、追記しました。 遅くなってしまい申し訳ありません。
guest

回答2

0

ベストアンサー

多分、もうひとりの回答者の人がいってるような場所に追加したせいだと思われる。

https://github.com/cakephp/app/commit/040cddab8e13960e5ebce5dcc3dadbedde39e683#diff-c9248b3167fc44af085b81db2e292837

CsrfProtectionMiddleware の登録は1回だけにしましょう

投稿2018/12/21 15:00

編集2018/12/21 15:01
退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

nori-p

2018/12/25 05:45

Application.phpが3.6版のコピーであることを失念しておりました。 ありがとうございました。
guest

0

こちらと同じ内容ではないでしょうか。
https://teratail.com/questions/138185

投稿2018/12/21 06:22

ozwind918

総合スコア1140

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2018/12/21 06:34

対処箇所としては同じだけど、 Cakephp 3.6 (だったかな) CSRF トークンの設定がデフォルト有効になった件だが、 提示のソースのではないはずよ。 ※ この問題は Form ヘルパーを使っていれば問題は起きない。(再起動とか途中でして無い限り)
nori-p

2018/12/21 06:44

FormHelperを使ってcreateしているので、別な問題と考えております。 src/Application.php の CsrfProtectionMiddleware は有効な状態です。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問