LoginSignup
0
0

More than 1 year has passed since last update.

Chapter4 その他のリクエスト・レスポンス処理(4-4)

Posted at

CSRF対策とVarifyCsrfToken

これまでフォームを作成した際には基本的にCSRF対策のための機能を組み込んでありました。
フォームの中にには@csrfという値が組み込んであり、
これによってCSRF対策用のトークンを出力する非表示フィールドが組み込まれました。

$exceptに追記する

「Middleware」の中に、「VerifyCsrfToken.php」がCSRF対策を行うためのファイル。
VerifyCsrfTokenクラスには標準で$exceptという変数は用意されています。
そこにm CSRF対策を適用しないアクションを設定します。

VerifyCsrfToken.php
class VerifyCsrfToken extends Middleware
{
    protected $except = [
        'hello',
    ];
    
}

上記の記述により、「/hello」にPOST送信された際には、
CSRF対策が実行されなくなります。
これによりフォームから@csrfを削除しても、
フォームが送信でき、問題なく処理することができます。
(対策されていない状態になるため、推奨はしない)

VerifyCsrfToken自体をOFFにするには?

Kernel.php
protected $middlewareGroups = [
        'web' => [            
            \App\Http\Middleware\VerifyCsrfToken::class,  **この記述を削除**            
        ],        
];

Kernel.phpの上記の記述を削除すると、
アプリケーション全体でVerifyCsrfTokenが読み込まれなくなり、CSRF対策がOFFになります。

クッキーを読み書きする

保存されているクッキーの値を取得する

sample.php
$変数 = $request->coolie(**キー**);

クッキーを新たに保存する

sample.php
$response->cookie(**キー**,****,**分数**);

<注意点>
クッキーを利用する場合、「値の保存と値の取得は用意されているオブジェクトが違う」。

  • 値の取得
    リクエストのcookieメソッドを利用し、
    引数には取得するクッキーのキー(保存する際に指定したもの)を渡します。
  • 値の保存
      レスポンスのcookieメソッドを利用し、
     引数には割り当てるキー(名前)、保存する値、そして保存期間を示す値(分数)を用意します。
HelloController.php
class HelloController extends Controller
{
    public function index(Request $request) {

        if ($request->hasCookie('msg'))
        {
            $msg = 'Cookie:' . $request->cookie('msg');
        } else {
            $msg = '*クッキーはありません。';
        }
        return view('hello.index',['msg'=>$msg]);

    }

    public function post(HelloRequest $request) {

        $validate_rule = [
            'msg' => 'required',
        ];
        $this->validate($request, $validate_rule);
        $msg = $request->msg;
        $response = response()->view('hello.index',['msg'=>'「' . $msg . '」をクッキーに保存しました。']);
        $response->cookie('msg',$msg,100);

        return $response;

    }

}
index.php
@section('content')

    <form action="/hello" method="post">
        <p>{{$msg}}</p>
        @if (count($errors) > 0)
            <p>入力に問題があります再入力してください</p>
        @endif

        <table>
            @csrf
            @if ($errors->has('msg'))
                <tr><th>ERROR</th><td>{{$errors->first('msg')}}</td></tr>
            @endif

            <tr><th>Message: </th><td><input type="text" name="msg" value="{{old('msg')}}"></td></tr>

            <tr><th></th><td><input type="submit" value="send"></td></tr>
        </table>

    </form>

@endsection

上手く挙動しなかったので、復習時に再検証

リダイレクトについて

sample.php
return redirect('/hello')

「redirect」という関数が、リダイレクトを実行するためのものです。
これは「ヘルパ」と呼ばれるものの一種で、面倒な処理を簡単な関数として呼び出せるようにしたものです。

リダイレクトを使いこなすには、「RedirectResponse」の使い方を覚える必要があります。

RedirectResponseの主なメソッド

入力データを付加する

sample.php
$response->withInput()

バリデータのエラーを付加する

sample.php
response->withErrors(**サービスプロバイダ**)

クッキーを付加する

sample.php
response->withCookie(**Cookie配列**)

Redirectorの主なメソッド

ルート及びアクションを指定する

sample.php
redirect(->route(**ルート名**, **配列**)
redirect(->action(**アクションの指定**, **配列**)

ビューを指定する

sample.php
redirect(->view(**ビュー**)

JSONデータを返す

sample.php
redirect(->json(**テキスト**)

ファイルを返す

sample.php
redirect(->download(**ファイルパス**)
redirect(->file(**ファイルパス**)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0